I was just wondering why __import__() calls a __init__ module twice when loading a package.
test.py
testpkg/
__init__.py
test.py:
pkg = __import__("testpkg", fromlist=[''])
__init__.py:
print "Called."
After calling python test.py, Called. will be printed out twice. Why does python execute the __init__ “module” twice?
This is a Python bug. Passing the null string as an element of
fromlistis illegal, and should raise an exception.There’s no need to include
""infromlist; that’s implicit–the module itself is always loaded. What’s actually happening is themodule.submodulestring is using the null string, resulting in the module nametestpkg., with a trailing period. That gets imported literally, and since it has a different name thantestpkg, it’s imported as a separate module.Try this:
… and you’ll see the duplicate module.
Someone should probably file a ticket on this if there isn’t already one; too tired to do it myself right now.