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?
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 *
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With