Skip to content
Advertisement

How to import package in module

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
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement