"import X" and "from X import y" produce different results, Why?

Tim Roberts timr at probo.com
Fri Mar 2 02:27:14 EST 2001


"Parzival Herzog" <parz at home.com> wrote:

>In the Essential Python Reference, it states (p. 72):
>
>"The from statement is identical to import, e3xcept that instead of creating
>a name referring to the newly created module namespace, references to one or
>more of the objects defined in the module are placed into the current
>namespace."
>
>So, apparently the imported X is a copy of xx.X, not the same object by
>another name.
>Can anyone explain this result? Is this result justified by a Python
>language specifcation?

Alex gave an excellent and detailed description of the issue here, but I
wonder if I could volunteer the mental model that helps me grasp this
concept.

>----------
># xx.py
>X = 35
>----------
># yy.py
>from xx import X
>import xx

At this point, there exists an object with the value "35".  The names
"xx.X" and "X" are both bound to that object.

>print "BEFORE, X =", X
>print "BEFORE, xx.X =", xx.X
>X = 99

At this point, there exists an object with the value "35".  xx.X is still
bound to that object.  There is also a NEW object with the value "99".  The
name "X" is bound to that object.

Assigning 99 to X did not change the value of the object X was bound to.
Rather, it created a new object and bound X to it.

>print "AFTER, X =", X
>print "AFTER, xx.X =", xx.X
>----------
--
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-list mailing list