6

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 to all core files into __init__.py to save repeating myself? What should go into __init__.py?

cjm2671
  • 18,348
  • 31
  • 102
  • 161

3 Answers3

3

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

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
1

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

According to docs in most cases yes, it is.

Artur
  • 973
  • 1
  • 14
  • 29
0

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 .curve import Curve 
from .some import SomethingElse

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

from core import Curve
Vikram Sangat
  • 136
  • 11