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

Answers


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


Need Your Help

Why is Python's 'all' function so slow?

python performance

I have wrote some very simple tests (I know, they are not 'conclusive', but they make me curious). I ran with optimization and all that jazz.

Sending 500 Error Information To Yourself

c# asp.net error-handling global-asax

Where would I need to hook in (at what event) to be able send myself every 500 error that happens on my current ASP.NET project. Something inside the global.asax? And I'd like to send myself the ou...