This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Double __init__.py executing
Type: Stage:
Components: Interpreter Core Versions:
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: kuskakus, loewis, paul.moore
Priority: normal Keywords:

Created on 2004-06-22 06:55 by kuskakus, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (3)
msg21238 - (view) Author: Alexandre (kuskakus) Date: 2004-06-22 06:55
There is some strange feature, looking like a bug.

I have 'pkg' dir with 2 files:

./pkg/__init__.py
print '__init__.py'

./pkg/test.py
print 'test.py'
import __init__


Python 2.3.4 (#53, May 25 2004, 21:17:02)
>>> import pkg.test
__init__.py
test.py
__init__.py

With '-v' option:

>>> import pkg.test
import pkg # directory pkg
# pkg\__init__.pyc matches pkg\__init__.py
import pkg # precompiled from pkg\__init__.pyc
__init__.py
# pkg\test.pyc matches pkg\test.py
import pkg.test # precompiled from pkg\test.pyc
test.py
# pkg\__init__.pyc matches pkg\__init__.py
import pkg.__init__ # precompiled from pkg\__init__.pyc
__init__.py

Why __init__.py executed two times?
msg21239 - (view) Author: Paul Moore (paul.moore) * (Python committer) Date: 2005-01-29 22:02
Logged In: YES 
user_id=113328

Essentially, because pkg\__init__.py is loaded into
sys.modules under *two* names. First, as pkg (as part of the
process of importing pkg.test) and then as pkg.__init__
(explicitly in pkg\test.py). As the source is loaded twice,
the print is executed twice.

While subtle, this is not a bug.

To demonstrate:

>>> import sys
>>> orig = set(sys.modules.keys())
>>> import pkg.test
init
init
test
>>> set(sys.modules.keys()) - orig
set(['pkg.test', 'pkg', 'pkg.__init__'])

You see, both pkg and pkg.__init__ are separately in
sys.modules (even though they refer to the same file).

In essence, it is incorrect to import __init__ directly -
always import the package. If test.py had said "import pkg",
you wouldn't have seen this behaviour, but nothing else
would have changed.
msg21240 - (view) Author: Martin v. Löwis (loewis) * (Python committer) Date: 2005-01-29 23:41
Logged In: YES 
user_id=21627

I agree with that analysis; closing this as invalid.
History
Date User Action Args
2022-04-11 14:56:04adminsetgithub: 40429
2004-06-22 06:55:07kuskakuscreate