When does code in __init__.py get run?

Python

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncrobarView Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow