tags:

views:

59

answers:

2

I have read in many posts that global variables are bad, but I need them!

My situation:

I have few variables defined in a dedicated module which are updated every minute and are used by other modules in the application. (Implemented after reading this), Do you think its a good approach or needs any improvement or any better idea?

Thanks

+2  A: 

This sounds like a good place for the pub/sub technique, where you have objects watch for changes. This is useful in things like GUIs, when you need to update some widget whenever the value it displays changes.

Something very simple:

>>> class Widget(object):
    def __init__(self, name, val):
        self.name = name
        self.val = val
    def update(self, val):
        self.val = val
        print self.name, "changed to", self.val


>>> def update(updateables, val):
    for u in updateables:
        u(val)


>>> w1, w2 = Widget("Alpha", 5), Widget("Beta", 6)
>>> updateables = [w1.update, w2.update]
>>> update(updateables, 17)
Alpha changed to 17
Beta changed to 17

The idea is that "observers" of the value register a callback, which gets invoked whenever that value changes.

Ryan Ginstrom
A: 

I think that's fine. You're not actually using globals (as in, using the 'global' keyword). You're importing a module and then accessing that module from other modules. Seems like a fine solution to me.

How much data are you moving around? Because you could use a datastore, like SQLite and each module could read and write to the datastore as needed. But with updates every minute you probably don't need persistance or relations, making your existing solution the simpler one.

[edited much later]

Come to think of it, an in-memory SQLite database might hit your sweet spot here: http://www.sqlite.org/inmemorydb.html

gomad