Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing across a python package

Tags:

python

pkg/
    __init__.py
    foo.py
    bar.py
    baz.py

I have a bunch of module imports that are the same across foo.py, bar.py, and baz.py.

Is there a way I can do the imports in __init__.py? What would I have to write in foo.py?

like image 580
Kamil Sindi Avatar asked Nov 02 '22 02:11

Kamil Sindi


2 Answers

Placing the imports in __init__.py would be a bad idea; __init__.py is used as the contents of your module object, so it is a public interface. Also, __init_.py is imported initially when your package is imported, while you don't actually need the imports to occur until your submodules need them.

The best approach is to put common code in an internal detail module, marked with a single initial underscore (meaning "private"), e.g. _imports.py, then in your other files write from ._imports import *.

like image 88
ecatmur Avatar answered Nov 15 '22 06:11

ecatmur


You guessed the right way of doing this, but I can make this a little more formal and give (hopefully) a clearer explanation than the one you found elsewhere. If you want to modularize imports, which depending on your coding philosophy could be a good or bad idea in and of itself (transparency vs. code reuse), whether or not the imports happen in __init__.py you can import your imports from another script. For instance:

"""import_scripts.py"""
import numpy as np
import scipy as sp
...

"""actual_code.py"""
from import_scripts import *
# np and sp are now in scope

Importing from __init__.py is mostly the same, you just traditionally use a relative import instead if you're accessing it from the same module:

# To import form __init__
from . import *

Important to note though, that these kind of imports will only work if you run these python scripts explicitly as modules rather than as scripts. This means:

python -m foo

instead of

python foo.py

Important, but subtle distinction.

Hope that helps. Let me know if you have any more questions.

like image 34
Slater Victoroff Avatar answered Nov 15 '22 06:11

Slater Victoroff