I’m new to Python, and I try to structure my Python application.
Given the following directory structure:
π¦app β£ πlexer β β£ πtoken β β β£ πtoken.py β β β£ πtype.py β β β π__init__.py β β π__init__.py β£ πtest β β£ πlexer β β β£ πtoken β β β β£ πtest_token.py β β β β π__init__.py β β β π__init__.py β β£ πtest_app.py β β π__init__.py β πapp.py
Right now, the application is executed using the following command:
pyhton -m app
When I try to execute the application using
python -m .app.py
The following error is raised:
Relative module names not supported.
Unit tests are being executed using:
python -m unittest
This works fine and without issues.
Now, I’m trying to use the import the token / type.py
file in the app.py
file.
The contents of this file are:
from enum import Enum, unique @unique class Type(Enum): UNKNOWN = 1 EOF = 2
The following import statement is added in the app.py
file:
from app.lexer.token.type import Type
Running the application right now yields the following error:
Traceback (most recent call last): File "C:Python38librunpy.py", line 193, in _run_module_as_main return _run_code(code, main_globals, None, File "C:Python38librunpy.py", line 86, in _run_code exec(code, run_globals) File "C:DEVDEMO.ONEappapp.py", line 17, in <module> from app.lexer.token.type import Type File "C:DEVDEMO.ONEappapp.py", line 17, in <module> from app.lexer.token.type import Type ModuleNotFoundError: No module named 'app.lexer'; 'app' is not a package
Any ideas on how this can be fixed?
Advertisement
Answer
app/
itself isn’t a package -since it doesn’t include a __init__
file-. app/
is root of the application, while the package’s path starts with lexer
. So, change
from app.lexer.token.type import Type
to
from lexer.token.type import Type