[New-bugs-announce] [issue13591] import_module potentially imports a module twice

Ryan Twitchell report at bugs.python.org
Mon Dec 12 22:43:24 CET 2011

New submission from Ryan Twitchell <metatheorem at gmail.com>:

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:


And the following file contents:


	import importlib


	import my_lib.bar

	# Or alternately
	#from . import bar


	from . import bar

	print('In foo, id(bar.baz): %s' % id(bar.baz))


	def baz():

	print('In bar, id(bar.baz): %s' % id(baz))

Running scratch.py results in my_lib.bar being imported twice:
$ 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 <report at bugs.python.org>

More information about the New-bugs-announce mailing list