Rebinding variable, despite global statement

Brian Leair telcom_sage at yahoo.com
Tue Aug 3 21:42:24 EDT 2004


> > I am using "from MyModule import *", (yes, yes, I know)
> > 
> > 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.
> 
> 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

Ah, thanks. This makes more sense now.

My module has a list of symbols that are availabel to it, the module's
dict. The keyword "global" is just a hint to assign to the symbol
stored in the module's dict instead of the function. I also didn't
quite realize that the "from X import " is really just adding entries
in my module's dict. In effect making copies. The g_my_var gets an
inital value from the import, but I really have MyPorgram.g_my_var and
MyModule.g_my_var and these names are independent.

A coworker commented that if g_my_var was bound to a modifiable object
(list, class, etc.) then the changes made to that object would be seen
in both places.

Thanks again.



More information about the Python-list mailing list