Message149358
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. |
|
Date |
User |
Action |
Args |
2011-12-12 21:43:24 | Ryan.Twitchell | set | recipients:
+ Ryan.Twitchell |
2011-12-12 21:43:24 | Ryan.Twitchell | set | messageid: <1323726204.09.0.608665838185.issue13591@psf.upfronthosting.co.za> |
2011-12-12 21:43:23 | Ryan.Twitchell | link | issue13591 messages |
2011-12-12 21:43:23 | Ryan.Twitchell | create | |
|