When does code in __init__.py get run?

Question:

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.

Asked By: crobar

||

Answers:

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.

Answered By: Martijn Pieters
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.