Rebinding variable, despite global statement
Peter Otten
__peter__ at web.de
Tue Aug 3 02:32:03 EDT 2004
Brian Leair wrote:
> I am using "from MyModule import *", (yes, yes, I know)
>
> MyModule has a variable "g_my_var" at the "global" scope.
>
> In the code that performs the import, I have a function that has the
> statement
> "global g_my_var". Despite this, when I try to assign to g_my_var it
> appears I am rebound to a different object.
> Beyond philosophical arguments about not using a "global" variable, is
> there a real reason why I can't assign to the global "g_my_var". I'm
> using python 2.3.2.
>
> One workaround is to place getter/setters in MyModule, but I was still
> surprised by this behavior.
Let's assume the current module is the main module __main__. After
from MyModule import *
or bettter
from MyModule import g_my_var
you have two independent bindings to the same object. You can think of it as
the two-step process
import MyModule
g_my_var = MyModule.g_my_var
# del MyModule
That you are using the same name in both __main__ and MyModule has no effect
on the general structure. With
def f():
global g_my_var
g_my_var = "some value"
f()
you only rebind g_my_var in the current module's global namespace (__main__
in the example).
While you should always think twice before modifying a module from the
outside, a reasonably clean way is to do it like so:
import MyModule
def f():
MyModule.g_my_var = "some value
f()
Peter
More information about the Python-list
mailing list