Why do directly imported variables behave differently than those attached to imported module?
Mel
mwilson at the-wire.com
Tue May 3 13:00:28 EDT 2011
Dun Peal wrote:
> Hi!
>
> Here's the demonstrating code:
>
> # module foo.py
> var = 0
>
> def set():
> global var
> var = 1
>
> Script using this module:
>
> import foo
> from foo import *
>
> print var, foo.var
> set()
> print var, foo.var
>
> Script output:
>
> 0 0
> 0 1
>
> Apparently, the `var` we imported from `foo` never got set, but
> `foo.var` on the imported `foo` - did. Why?
They're different because -- they're different. `foo.var` is defined in the
namespace of the foo module. Introspectively, you would access it as
`foo.__dict__['var']` .
Plain `var` is in your script's namespace so you could access it as
`globals()['var']` . The values given to the vars are immutable integers,
so assignment works by rebinding. The two different bindings in
foo.__dict__ and globals() get bound to different integer objects.
Note too the possible use of `globals()['foo'].__dict__['var'] . (Hope
there are no typos in this post.)
Mel.
More information about the Python-list
mailing list