79170299

Date: 2024-11-08 13:53:41
Score: 1.5
Natty:
Report link

Relative imports in Python, from one directory up

Let's imagine you have this directory structure:

dev/
    my_project/
        config.py
        sandbox/
            test.py

And you want to cd into my_project and run test.py, where test.py imports config.py. Python doesn't allow this by default: you cannot import anything from above your current directory, unless you use sys.path.insert() to insert that upper directory into your system path first, before attempting the import.

So, here's the call you want to make:

cd dev/my_project
./sandbox/test.py

And here's how to allow test.py to import config.py from one directory up:

test.py:

#!/usr/bin/env python3

import os
import sys

# See: https://stackoverflow.com/a/74800814/4561887
FULL_PATH_TO_SCRIPT = os.path.abspath(__file__)
SCRIPT_DIRECTORY = str(os.path.dirname(FULL_PATH_TO_SCRIPT))
SCRIPT_PARENT_DIRECTORY = str(os.path.dirname(SCRIPT_DIRECTORY))
# allow imports from one directory up by adding the parent directory to the 
# system path
sys.path.insert(0, f"{SCRIPT_PARENT_DIRECTORY}")

# Now you can import `config.py` from one dir up, directly!
import config

# The rest of your imports go here...


# The rest of your code goes here...

References

  1. My original answer where I first posted this content: How do I get the path and name of the python file that is currently executing?

Going further

  1. In Bash, which can be rather Pythonic by using if [ "$__name__" = "__main__" ], relative imports are more natural, and are done as follows:
    1. [main resource] My article on my website: GabrielStaples.com: How do you write, import, use, and test libraries in Bash?
    2. My answer: Importing functions from a shell script
    3. My answer: How do I get the directory where a Bash script is located from within the script itself?
Reasons:
  • Blacklisted phrase (1): How do I
  • Blacklisted phrase (1): How do you
  • Blacklisted phrase (1): stackoverflow
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • High reputation (-2):
Posted by: Gabriel Staples