Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__import__() calls __init__.py twice?

Tags:

python

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?

like image 974
Manuel Faux Avatar asked Dec 29 '22 07:12

Manuel Faux


1 Answers

This is a Python bug. Passing the null string as an element of fromlist is illegal, and should raise an exception.

There's no need to include "" in fromlist; that's implicit--the module itself is always loaded. What's actually happening is the module.submodule string is using the null string, resulting in the module name testpkg., with a trailing period. That gets imported literally, and since it has a different name than testpkg, it's imported as a separate module.

Try this:

pkg = __import__("testpkg", fromlist=[''])
import sys
print sys["testpkg"]
print sys["testpkg."]

... 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.

like image 62
Glenn Maynard Avatar answered May 14 '23 19:05

Glenn Maynard