classification
Title: __package__ is None in __init__.py until an import is used
Type: Stage: resolved
Components: Library (Lib) Versions: Python 2.7
process
Status: closed Resolution: wont fix
Dependencies: Superseder:
Assigned To: Nosy List: Yuval S, eric.snow, ncoghlan
Priority: normal Keywords:

Created on 2019-10-12 21:48 by Yuval S, last changed 2019-10-20 12:54 by ncoghlan. This issue is now closed.

Messages (3)
msg354555 - (view) Author: Yuval S (Yuval S) * Date: 2019-10-12 21:48
In Python 2.7, the __package__ variable isn't set when __init__.py is run, until an import is done. In Python 3.5, it is set correctly.

e.g.

# mkdir x && echo "print(__package__)" | tee x/__init__.py x/test.py
# python2 x.test
None
x
# python3 x.test
x
x
# echo -e "import os\n$(cat x/__init__.py)" > x/__init__.py
# python2 x.test
x
x

This is very old, as it's there at least since 2010: https://stackoverflow.com/questions/4437394/package-is-none-when-importing-a-python-module 

I would expect Python 2 and 3 to behave the same.
msg354567 - (view) Author: Yuval S (Yuval S) * Date: 2019-10-13 07:43
* It should be python[23] -m x.test, of course.
msg354998 - (view) Author: Nick Coghlan (ncoghlan) * (Python committer) Date: 2019-10-20 12:54
Yes, this is a design flaw in the Python 2 import system - it derives `__package__` from `__name__` the first time it needs the information and `__package__` isn't already set.

The problem was fixed for the Python 3 series by way of PEP 451, which made substantial changes to the way module initialisation works, allowing the import system to instead derive `__package__` from `__spec__` as part of module creation.

Depending on your reasons for being interested in this, the `importlib2` package may be of interest: https://pypi.org/project/importlib2/

(Judging from the version number, Eric last updated that for Python 3.5, which means it will include the PEP 451 behaviour)
History
Date User Action Args
2019-10-20 12:54:00ncoghlansetstatus: open -> closed
resolution: wont fix
messages: + msg354998

stage: resolved
2019-10-18 18:34:12brett.cannonsetnosy: - brett.cannon
2019-10-18 18:34:09brett.cannonsetnosy: + brett.cannon, ncoghlan, eric.snow
2019-10-18 18:34:00brett.cannonsetnosy: - brett.cannon
2019-10-13 07:43:25Yuval Ssetmessages: + msg354567
2019-10-13 00:24:22xtreaksetnosy: + brett.cannon
2019-10-12 21:48:12Yuval Screate