Perplexed by the behavior of import

Rod Kosloski rkosloski at visi.com
Tue Jan 10 11:01:45 EST 2012


I'm perlexed by an apparent inconsistency in the behavior of the import
statement.
First, the files. There is a simple package, pkg, containing two files: mod.py
and util.py, and a stand-alone module also named util.py:
 *** ./pkg/__init__.py ***
 from mod import *
 *** ./pkg/mod.py ***
 M = 8
 *** ./pkg/util.py ***
 V = 0
 *** ./util.py ***
 from pkg import *
 from pkg.util import *
 U = 0
Next, the Python session:
 Python 2.6.4 (r264:75706, Dec 13 2009, 19:46:11)
 [GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
 Type "help", "copyright", "credits" or "license" for more information.
 >>> import util
 >>> globals()
 {'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__',
 '__doc__': None 'util': <module 'util' from 'util.pyc'>, '__package__':
 None}
 >>> from pkg import *
 >>> globals()
 {'__builtins__': <module '__builtin__' (built-in)>, 'M': 8, '__package__':
 None, 'util': <module 'pkg.util' from 'pkg/util.pyc'>, '__name__':
 '__main__', '__doc__': None,
 'mod': <module 'pkg.mod' from 'pkg/mod.pyc'>}
Compare the output of the two globals() statements:
Variable util's value has changed from <module 'util' from 'util.py'....> to
<module 'pkg.util'...>
What's happening to util?
OK, maybe pkg.util replaces the original util because of the pkg import
statement. But then, what about the following:
 Python 2.6.4 (r264:75706, Dec 13 2009, 19:46:11)
 [GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
 Type "help", "copyright", "credits" or "license" for more information.
 >>> util = 0
 >>> globals()
 {'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__',
 '__doc__': None, 'util': 0, '__package__': None}
 >>> from pkg import *
 >>> globals()
 {'__builtins__': <module '__builtin__' (built-in)>, 'M': 8, '__package__':
 None, 'util': 0, '__name__': '__main__', '__doc__': None, 'mod': <module
 'pkg.mod' from 'pkg/mod.pyc'>}
 >>>
Now the value of util is unchanged across the pkg import statement.
Why the difference?
Thanks.


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /