Vahid Kharazi
Vahid Kharazi

Reputation: 6033

Importing from a file in previous path in python

I have this file structure:

.
   test/db_test.py
   models/user.py

I want to import user.py in db_test.py, for example i try it:

from ..models.user import User

but have this error:

SystemError: Parent module '' not loaded, cannot perform relative import

How can do this work?

  1. all path have __init__.py file
  2. i don't want to use appending in sys.path

thank for your answers

Upvotes: 1

Views: 364

Answers (1)

djhoese
djhoese

Reputation: 3667

Have you tried running the script as a package? Try running the following from the directory containing your package root directory:

python -m your_package_name.test.db_test

My test that this worked for was:

your_package_name/
    __init__.py
    test/
        __init__.py
        db_test.py
    models/
        __init__.py
        user.py

Where "db_test.py" contained:

from ..models.user import User

So I ran that command from the parent directory of "your_package_name".

Upvotes: 1

Related Questions