I have read the documentation and there is something I'm still not sure about. Does all the initialisation code for the whole module in __init__.py
get run if I do:
from mymodule import mything
or only if I do
import mymodule
What gets run from __init__.py
and when does it get run?
I'm sure I could also test this fairly easy, but for posterity and helpfulness for others, I thought I'd ask here.
The __init__.py file makes Python treat directories containing it as modules. Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.
Leaving an __init__.py file empty is considered normal and even a good practice, if the package's modules and sub-packages do not need to share any code.
So it's normally a good place to put any package-level initialisation code. The bottom line is: all names assigned in __init__.py , be it imported modules, functions or classes, are automatically available in the package namespace whenever you import the package or a module in the package.
If you have setup.py in your project and you use find_packages() within it, it is necessary to have an __init__.py file in every directory for packages to be automatically found.
The code in __init__.py
is run whenever you import anything from the package. That includes importing other modules in that package.
The style of import (import packagename
or from packagename import some_name
) doesn't matter here.
Like all modules, the code is run just once, and entered into sys.modules
under the package name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With