Perplexed by the behavior of import

Peter Otten __peter__ at web.de
Tue Jan 10 11:40:04 EST 2012


Rod Kosloski wrote:

> 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. 

That's indeed what happens.

> 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?

As long as you haven't imported the pkg.util module there isn't an "util" 
variable in the pkg namespace:

$ python -c 'import pkg; print "util" in vars(pkg); import pkg.util; print 
"util" in vars(pkg)'
False
True

Or, sticking closer to your example:

$ python -c 'util = 0; from pkg import *; print util'
0
$ python -c 'util = 0; import pkg.util; from pkg import *; print util'
<module 'pkg.util' from 'pkg/util.pyc'>





More information about the Python-list mailing list