I have the following directory structure:
application
tests
main.py
main.py
application/main.py contains some functions.
You cannot import things from parent/sibling directories as such. You can only import things from directories on the system path, or the current directory, or subdirectories within a package. Since you have no __init__.py
files, your files do not form a package, and you can only import them by placing them on the system path.
First of all you need to make your directories into packages, by adding __init__.py
files:
application
tests
__init__.py
main.py
__init__.py
main.py
Then you should make sure that the directory above application is on sys.path
. There are many ways to do that, like making the application infto a package and installing it, or just executing things in the right folder etc.
Then your imports will work.
in python . exists for same directory, .. for parent directory to import a file from parent directory you can use ..
from .. import filename (without .py extension)
If you'd like your script to be more portable, consider finding the parent directory automatically:
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# import ../db.py
import db
To import a file in a different subdirectory of the parent directory, try something like this:
sys.path.append(os.path.abspath('../other_sub_dir'))
import filename_without_py_extension
Edit: Missing closing bracket.
You must add the application dir to your path:
import sys
sys.path.append("/path/to/dir")
from app import object
Or from shell:
setenv PATH $PATH:"path/to/dir"
In case you use windows: Adding variable to path in windows.
Or from the command line:
set PATH=%PATH%;C:\path\to\dir