__import __ () calls __init__.py twice?

I'm just wondering why the __import__()module is called twice __init__when loading the package.

test.py
testpkg/
        __init__.py

test.py:

pkg = __import__("testpkg", fromlist=[''])

__init__.py:

print "Called."

After the call python test.py, Called. will be printed twice. Why does python execute a module twice __init__?

+3
source share
2 answers

This is a Python bug. Passing a null string as an element fromlistis illegal and should throw an exception.

"" fromlist; - . module.submodule , testpkg. . , , testpkg, .

:

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

... .

- , , , ; , .

+5

fromlist=[''] hack python-dev. , , fromlist , , .

, importlib.import_module ( Python 2.7 Python 3.1 PyPI Python 2.3 Django 1.1 django.utils.importlib). , .

importlib (, PyPI , , , PSF, ), __import__("some.module"); mod = sys.modules["some.module"]. , python-dev ( , importlib).

+5

Source: https://habr.com/ru/post/1765493/


All Articles