I would like a way to detect if my module was executed directly, as in import module
or from module import *
rather than by import module.submodule
(which also executes module
), and have this information accessible in module
's __init__.py
.
Here is a use case:
In Python, a common idiom is to add import statement in a module's __init__.py
file, such as to "flatten" the module's namespace and make its submodules accessible directly. Unfortunately, doing so can make loading a specific submodule very slow, as all other siblings imported in __init__.py
will also execute.
For instance:
module/
__init__.py
submodule/
__init__.py
...
sibling/
__init__.py
...
By adding to module/__init__.py
:
from .submodule import *
from .sibling import *
It is now possible for users of the module to access definitions in submodules without knowing the details of the package structure (i.e. from module import SomeClass
, where SomeClass is defined somewhere in submodule
and exposed in its own __init__.py
file).
However, if I now run submodule
directly (as in import module.submodule
, by calling python3 -m module.submodule
, or even indirectly via pytest) I will also, unavoidably, execute sibling
! If sibling is large, this can slow things down for no reason.
I would instead like to write module/__init__.py
something like:
if __???__ == 'module':
from .submodule import *
from .sibling import *
Where __???__
gives me the fully qualified name of the import. Any similar mechanism would also work, although I'm mostly interested in the general case (detecting direct executing) rather than this specific example.