This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author Ryan.Twitchell
Recipients Ryan.Twitchell
Date 2011-12-12.21:43:23
SpamBayes Score 1.3680677e-06
Marked as misclassified No
Message-id <1323726204.09.0.608665838185.issue13591@psf.upfronthosting.co.za>
In-reply-to
Content
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.
History
Date User Action Args
2011-12-12 21:43:24Ryan.Twitchellsetrecipients: + Ryan.Twitchell
2011-12-12 21:43:24Ryan.Twitchellsetmessageid: <1323726204.09.0.608665838185.issue13591@psf.upfronthosting.co.za>
2011-12-12 21:43:23Ryan.Twitchelllinkissue13591 messages
2011-12-12 21:43:23Ryan.Twitchellcreate