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: 'from app import __init__' behaves differently with native import and importlib
Type: behavior Stage: resolved
Components: Library (Lib) Versions: Python 3.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: qagren, serhiy.storchaka
Priority: normal Keywords:

Created on 2018-10-26 05:31 by qagren, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (4)
msg328512 - (view) Author: Quentin Agren (qagren) * Date: 2018-10-26 05:31
I'm running Python 3.6 on Ubuntu 16.04

I don't know if this should qualify as a bug, but I noticed the following behavior difference in the (contrived?) scenario of directly importing '__init__' from a package:

## Setup ##

mkdir app
echo 'print(f"Executing app/__init__.py as {__name__}")' > app/__init__.py

## Native: executes __init__ *once* ##

python -c 'from app import __init__'
# Output:
# Executing app/__init__.py as app

## Importlib: executes __init__ *twice* ##

python -c "import importlib; importlib.import_module('.__init__', 'app')"
# Output:
# Executing app/__init__.py as app
# Executing app/__init__.py as app.__init__

Note in addition that absolute import (either with importlib or native) executes '__init__' twice.
msg328513 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2018-10-26 05:58
`from app import __init__` is equivalent to `importlib.import_module('app').__init__`.

`importlib.import_module('.__init__', 'app')` is equivalent to `import app.__init__`.
msg328518 - (view) Author: Quentin Agren (qagren) * Date: 2018-10-26 07:47
Sorry for the misunderstanding, and thanks for clarifying!

So essentially what I am getting by `from app import __init__` is the `__init__` method of the module object bound to the name `app`.

However if I have a submodule `app/myapp.py`, `from app import myapp` will import it and bind it to the name `myapp`, whereas `importlib.import_module('app').myapp` raises AttributeError, so I guess the two forms not totally equivalent...


Anyways, I'll investigate deeper before creating an issue henceforth :)
msg328522 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2018-10-26 08:17
The difference is that attribute "__init__" existed. If you set the "myapp" global in the "app" module, the file "app/myapp.py" will be not imported.
History
Date User Action Args
2022-04-11 14:59:07adminsetgithub: 79254
2018-10-26 08:17:37serhiy.storchakasetresolution: not a bug
messages: + msg328522
2018-10-26 07:47:18qagrensetstatus: open -> closed

messages: + msg328518
stage: resolved
2018-10-26 05:58:47serhiy.storchakasetnosy: + serhiy.storchaka
messages: + msg328513
2018-10-26 05:31:45qagrencreate