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:
Could you please help me understand how to properly import BaseModel from src.database.models?
UPDATE: So, I found a solution with help of Claude Sonnet. The problem was in incorrect path.
This is a correct import statement:
current_path = os.getcwd() # This is already '/github' based on your logs
sys.path.insert(0, current_path) # Insert at beginning of path for priority
try:
# Direct import of the module
base_module = importlib.import_module('src.database.models.base')
# Get the BaseModel class from the module
base = getattr(base_module, 'BaseModel')
print(f"Successfully imported BaseModel from {base.__module__}")
except Exception as e:
print(f"Import error: {e}")
