Where is my namespace?

Simon Brunning simon at brunningonline.net
Mon Dec 7 11:25:39 EST 2009


2009/12/7 vsoler <vicente.soler at gmail.com>:
> I take the example from Mark Lutz's excellent book "Learning Python".
>
> *** In nested1.py  I have:
> X=99
> def printer(): print X
>
> *** In nested2.py  I have:
> from nested1 import X, printer
> X=88
> printer()
>
> What is amazing is that running nested2.py prints 99 and not 88.
>
> My questions are:
>
> 1. Using statement "from" instead of "import" should not create a
> namespace, at least that's what I think. However, the printer()
> function is able to find 99 which is residing in...  a namespace?

Sorry - you think wrong. All modules have their own namespace.

"from blah import" injects the objects from the imported module
directly into the importing modules namespace, but they are still two
distinct namespaces.

> 2. I have tried to access the 88 by qualification from nested2.py.
> However, I cannot. If using "print nested1.X" in nested2.py I get an
> error

If you do "from blah import" the imported module itself isn't bound to
any name in the importing module - you can't get at it at all.

> 3. Mark says: The from statement is really an assignment to names in
> the importer's scope--a name-copy operation, not a name aliasing.   I
> don't fully understand what he means. Could anybody explain?

Does the above help?

-- 
Cheers,
Simon B.



More information about the Python-list mailing list