Skip to content Skip to sidebar Skip to footer

Python Imports With __init__.py

No matter how I structure the imports in the code files and in the __init__.py files, I can't seem to get it right for executing the program and running the tests using pytest. How

Solution 1:

You'd better use relative imports.

When doing from src import * in src/__init__.py you'll only import anything you've defined before calling the import. Most likely that's just nothing. If you've defined the __all__ variable, you'll get the submodule from it, but maybe also an AttributeError if a variable hasn't been defined yet.

So instead import the modules you need explicitly where you need them like

from .VocableFileWriterimportVocableFileWriterfrom .exceptions.XMLInvalidExceptionimportXMLInvalidException

or lets say within src/gui/GTKSignal.py

from ..exceptions.XMLInvalidExceptionimportXMLInvalidException

Also you could use project-absolute paths like mentioned in your Edit#2.


Furthermore you've a problem with your path when calling ./src/main.py. In this case the directory containing src is not in the path. Instead ./src/ is in the path. Therefore python doesn't consider it a package anymore and since there's no other package with that name available, the import fails.

Instead put your main.py module in the same directory like the src package or call it as a module with python -m src.main. Doing so you could also rename it to src/main.py and call the package instad with python -m src.


When using the first approach, main should use an absolute import structure. Just think of it as a module you put anywhere on your computer, while your src package is somewhere else, where it can be found by Python, like any other module or package installed by the system. It's not different, when it's located besides the package itself, since the current directory is in sys.path.

main.py

import os
import sys
from src.VocableFileWriterimportVocableFileWriterfrom src.XLDAttributeValueAdderimportXLDAttributeValueAdder

Post a Comment for "Python Imports With __init__.py"