Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does code in __init__.py get run?

Tags:

python

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.

like image 666
crobar Avatar asked Nov 26 '14 08:11

crobar


People also ask

What does __ init __ py do in Python?

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.

Should __ init __ py be empty?

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.

Should you put code in init py?

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.

Is __ init __ py required?

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.


Video Answer


1 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.

like image 182
Martijn Pieters Avatar answered Oct 23 '22 22:10

Martijn Pieters