New submission from Ryan Twitchell :
Use of importlib's import_module function with modules belonging to a library
can cause some modules to be imported twice, if such a module is referenced
from sibling modules, and from __init__ in the package. I suspect this is a
bug, or at best a nuance of packages that is quite subtle.
Easier to show with an example. Below, the module my_lib.bar will be imported
twice. Given the following file structure:
./scratch.py
./my_lib/__init__.py
./my_lib/foo.py
./my_lib/bar.py
And the following file contents:
./scratch.py:
import importlib
importlib.import_module('my_lib.bar')
importlib.import_module('my_lib.foo')
./my_lib/__init__.py:
import my_lib.bar
# Or alternately
#from . import bar
./my_lib/foo.py:
from . import bar
print('In foo, id(bar.baz): %s' % id(bar.baz))
./my_lib/bar.py:
def baz():
pass
print('In bar, id(bar.baz): %s' % id(baz))
Running scratch.py results in my_lib.bar being imported twice:
$ echo $PYTHONPATH
.
$ python --version
Python 3.2.2
$ python ./scratch.py
In bar, id(bar.baz): 21328632
In bar, id(bar.baz): 21352240
In foo, id(bar.baz): 21352240
Replacing the calls to import_module with use of the import statement, or
__import__, or simply rearranging the order of the two calls all result in the
module my_lib.bar to be imported only once. As does eliminating the import
statement in my_lib.__init__.
This may be a misunderstanding on my part regarding the intended use of
packages, but this behavior was quite unexpected, and rather difficult to track
down in real code.
--
components: Library (Lib)
messages: 149358
nosy: Ryan.Twitchell
priority: normal
severity: normal
status: open
title: import_module potentially imports a module twice
type: behavior
versions: Python 3.2
___
Python tracker
<http://bugs.python.org/issue13591>
___
___
Python-bugs-list mailing list
Unsubscribe:
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com