1

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

Charles
  • 50,943
  • 13
  • 104
  • 142
Vahid Kharazi
  • 5,723
  • 17
  • 60
  • 103

1 Answers1

1

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".

djhoese
  • 3,567
  • 1
  • 27
  • 45
  • I should note that I don't normally work with python 3 so no guarantees. – djhoese Feb 01 '14 at 20:01
  • it's worked, but i don't want run an script like an module and `from ..models.user import User` don't work! – Vahid Kharazi Feb 01 '14 at 20:25
  • Unless this changed in python 3, you can't use relative imports from a non-package context. A relative import means you are importing relative to your current package/subpackage. If you want to run it as a script I think you'll have to have the necessary modules in your sys.path. – djhoese Feb 01 '14 at 23:13