crobar
crobar

Reputation: 2929

When does code in __init__.py get run?

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.

Upvotes: 70

Views: 35014

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121168

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.

Upvotes: 77

Related Questions