Twice instanciation

Manuel Garcia news at manuelmgarcia.com
Thu Jun 12 19:12:08 EDT 2003


On Thu, 12 Jun 2003 22:45:09 +0200, Salvatore <artyprog at wanadoo.fr>
wrote:

>The problem araise when I was asked from a friend how to manage
>global variables, and among other examples I said he could wrote
>a class named Global and instanciate object from this class,
>being assured a same name would not be used twice

Hmm, I would put the data inside a module.  A module automatically has
the behavior that it is loaded only once, and the standard way of
importing a module makes you use the filename as the name.

So I would make a module named 'my_global.py', and make sure the
directory it was in was on my 'PYTHONPATH'.

# my_global.py
# ############ #
d = {
    'global01':'hello',
    'global02':'goodbye',
    'global03':17
    }
# ############ #

And no matter how many modules I have opened, 'import my_global'
always sets 'my_global' to the exact same module.

So if in one module I do:

    import my_global
    my_global.d['global03'] = 29

later on, in any of another modules I may have running,

    import my_global
    assert my_global.d['global03'] == 29

will be true (unless I changed it in the meantime, of course).

So easy to do with a module, it is hardly worth the bother of making a
class with similar behavior.

Manuel




More information about the Python-list mailing list