Why do directly imported variables behave differently than those attached to imported module?

Daniel Kluev dan.kluev at gmail.com
Tue May 3 12:57:51 EDT 2011


On Wed, May 4, 2011 at 3:31 AM, Dun Peal <dunpealer at gmail.com> wrote:
> Apparently, the `var` we imported from `foo` never got set, but
> `foo.var` on the imported `foo` - did. Why?

Because all names are references to some values, not other names (in
CPython, it means all names are PyObject*, and point directly to the
objects, not other pointers)

When you do `from foo import bar` it assigns globals()['bar'] of
current module to reference same value as `foo.bar`. Its now local
namespace name, not `foo` namespace, and therefore functions in `foo`
cannot modify this namespace.

Since ints are immutable, when you do `var = 1` you create new object
of type int, and re-assign `var` name to point to new object.

`foo.var`, on other hand, is a way to access `foo`'s own namespace, so
its exactly same name as globals()['var'] of `foo`.

-- 
With best regards,
Daniel Kluev



More information about the Python-list mailing list