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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With