[Python] How to properly import python module from another python file using...

Discussão em 'Python' iniciado por Stack, Maio 1, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working on Alembic migration github action and need to import base metadata class inside python migration script which locates in another directory. I can't import it directly inside python migration script like as it's normally do like from src.databse.models import BaseModel because it's dynamically provided thru migration script parameter.

    So I decided to import it using importlib.import_module but get an error No module named 'BaseModel'

    Here is the log from github action:

    Current directory: /github
    Content of current directory: ['LICENSE.md', '.dockerignore', '.github', '.git', 'Dockerfile', 'docker-compose.yml', 'src', 'migrations', '.gitignore', 'alembic.ini', 'pyproject.toml', 'Makefile', 'poetry.lock', 'README.md']
    Parent directory: /
    Parent directory content: ['run', 'bin', 'sys', 'var', 'lib', 'tmp', 'sbin', 'srv', 'mnt', 'home', 'opt', 'etc', 'dev', 'proc', 'media', 'lib64', 'boot', 'usr', 'root', 'github', '.dockerenv', 'entrypoint.sh', 'check_alembic_migration.py']
    ERROR applying migrations: No module named 'BaseModel'


    And here the my code where I'm trying to import BaseModel:

    print("Current directory:", os.path.dirname(os.getcwd()))
    print("Content of current directory:", os.listdir(os.getcwd()))
    print("Parent directory:", os.path.dirname(os.path.dirname(os.getcwd())))
    print("Parent directory content:", os.listdir(os.path.dirname(os.path.dirname(os.getcwd()))))

    sys.path.append(os.path.dirname(os.getcwd()))

    base = importlib.import_module("BaseModel", "src.database.models")


    src is my app package

    check_alembic_migration.py is migration script where I'm trying to do import

    Here is project structure:

    [​IMG]

    Could you please help me understand how to properly import BaseModel from src.database.models?

    Continue reading...

Compartilhe esta Página