I’m having difficulties with using internal imports inside my projects. This is a partial tree structure of my project:
app
|- Gui.py
|- Main.py
|- logger.py
|- config.py
|- WebParser (package)
|- __init__.py
|- LinksGrabber.py
|- LyricsGrabber.py
|- ImagesGrabber.py
|- (Many other packages...)
the logger.py and config.py modules are required in every package’s modules, and are independent (uses only bulit-in modules). It is tricky to access these modules from inside packages.
This is how I tried to achieve it, for enabling configuration access and logging feature in WebParser\LinksGrabber.py:
# WebParser\__init__.py:
sys.path.append('..') # for outside-package modules
import config
from logger import log
# WebParser\LinksGrabber.py:
import WebParser
config = WebParser.config
log = WebParser.log
The Problems:
- This has code smell. I bet there is a better way to achieve this behaviour.
- I want to call
import WebParserand useWebParser.LinksGrabberandWebParser.LyricsGrabberright away, without implicitly importing them. This can be done with importing the modules inside__init__.py, but it isn’t possible because every package’s module imports the package itself, and it will issue recursive imports.
Can you suggest a better implemention, or a different code design?
You should make
appa package by giving it an__init__.pyfile. The python relative import system only works inside packages. Then inside your WebParser modules, you can dofrom .. import config,from .. import Gui, etc.As for importing WebPackage from the packages inside it, that is a bit of a code smell. Why do you need to do that? Using relative imports you could instead, for instance, have
from . import LinksGrabberinside ImagesGrabber, etc., to access what you need. If there are functions that are part of the WebParser package that are needed by many of the submodules, you should pull those out into a separate module in WebParser.