Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #18769
| Newsgroups | comp.lang.python |
|---|---|
| Subject | Perplexed by the behavior of import |
| From | Rod Kosloski <rkosloski@visi.com> |
| Date | 2012-01-10 10:01 -0600 |
| Message-ID | <m2sjjno8ba.fsf@news.visi.com> (permalink) |
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.
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
Perplexed by the behavior of import Rod Kosloski <rkosloski@visi.com> - 2012-01-10 10:01 -0600 Re: Perplexed by the behavior of import Peter Otten <__peter__@web.de> - 2012-01-10 17:40 +0100
csiph-web