[Python] python importlib from subdirectory, module not found

Discussão em 'Python' iniciado por Stack, Fevereiro 11, 2025.

  1. Stack

    Stack Membro Participativo

    I'v been struggling with importing a sub module. In main.py two modules are imported located under 220_04_070. I'm using importlib since the directory name only consist of numbers. common.py just contains a number of variables.

    The problem I get is:

    .../220_04_070/unicorn.py", line 1, in <module>
    from common import *
    ModuleNotFoundError: No module named 'common'.


    I can get around by adding a dot in front of common in unicorn.py. But since unicorn is used standalone at other parts I prefer not to do that.

    from .common import *


    Both main.py and unicorn.py are using common.py. The structure is as below:

    |-- main.py
    |
    |-- 220_04_070
    |-- common.py
    |-- unicorn.py


    main.py

    import importlib
    uc = importlib.import_module('220_04_070.unicorn')
    cm = importlib.import_module('220_04_070.common')

    mycorn = uc.unicorn()


    unicorn.py

    from common import *
    class unicorn():
    def __init__(self):
    None


    All is run with python3.12.3 (Ubuntu 24.04).

    So, my question is how I should handle this?

    Continue reading...

Compartilhe esta Página