Skip to content Skip to sidebar Skip to footer

Is __init__.py Run Everytime I Import Anything From That Module?

I've got a module called core, which contains a number of python files. If I do: from core.curve import Curve Does __init__.py get called? Can I move import statements that apply

Solution 1:

I've got a module called core, which contains a number of python files.

if it contains python files, it's not a module, it's a directory containing python files - and eventually a package if it contains an __init__.py file.

If I do: from core.curve import Curve does __init__.py get called?

It's never "called" - it's not a function - but it gets loaded the first time the package or one of it's submodules gets imported in a process. It's then stored in sys.modules and subsequent imports will find it there.

Can I move import statements that apply to all core files into init.py to save repeating myself?

Nope. namespaces are per-module, not per-package. And it would be a very bad idea anyway, what you name "repeating yourself" is, in this case, a real helper when it comes to maintaining your code (explicit imports means you know without ambiguity which symbol comes from which module).

What should go into init.py?

Technically you can actually put whatever you want in your __init__.py files, but most often than not they are just empty. A couple known uses case are using it as a facade for the package's submodules, selecting a concrete implementation for a common API based on thye current platform or some environment variable etc...

Oh and yes: it's also a good place to add some meta informations about your package (version, author etc).

Solution 2:

Is __init__.py run everytime I import anything from that module?

According to docs in most cases yes, it is.

Solution 3:

You can add all your functions that you want to use in your directory

- core
  -__init__.py

in this __init__.py add your class and function references like

from .curveimportCurvefrom .someimportSomethingElse

and where you want to User your class just refer it like

from core importCurve

Post a Comment for "Is __init__.py Run Everytime I Import Anything From That Module?"