how can I modify an imported variable ?

Jean-Paul Calderone exarkun at divmod.com
Wed Dec 27 10:14:36 EST 2006


On Wed, 27 Dec 2006 14:50:18 GMT, yomgui <not at valid.com> wrote:
>I've tried this:
>
>import MyPackage
>if MyPackage.aVariable is None:
>     MyPackage.aVariable = True
>
>but when I tried to access MyPackage.aVariable from another file
>(ie through an other import) the value is still None.
>
>
>how can I do this
>
>thanks
>
>yomgui

You have the right idea, but you must have overlooked something.  Consider
this:

    exarkun at charm:~$ cat > foo.py
    a = None
    exarkun at charm:~$ cat > bar.py
    import foo
    foo.a = 10
    exarkun at charm:~$ cat > baz.py
    import bar
    import foo
    print foo.a
    exarkun at charm:~$ python baz.py
    10
    exarkun at charm:~$

However, think about avoiding this pattern.  Instead of using globals
to track state, define a class, create an instance, and pass it to the
different functions and methods of your program so that they can inspect
and mutate it.  If you use globals, you will end with code which is harder
to unit test and harder to re-use.

Jean-Paul



More information about the Python-list mailing list