Skip to content

Instantly share code, notes, and snippets.

@justinmklam
Last active May 7, 2024 21:05
Show Gist options
  • Save justinmklam/c453ea62b47f4e302dbd83c05882e3bd to your computer and use it in GitHub Desktop.
Save justinmklam/c453ea62b47f4e302dbd83c05882e3bd to your computer and use it in GitHub Desktop.
Techniques for python path manipulation and relative imports in (i.e. when not dealing with a package).

Paths

import os

# To get the directory of the script/file:
current_dir = os.path.dirname(os.path.realpath(__file__))

# To get one directory up from the current file
parent_dir = os.path.abspath(os.path.join(current_dir, ".."))

Imports

For simple project structures:

import sys, os
sys.path.insert(1, os.path.join(sys.path[0], '..'))

When absolute paths are required:

import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)

Alternative to the above (good for multiple paths):

import sys, os
currentdir = os.path.dirname(__file__)
srcdirs = ['../../path1', '../path2']

for src in srcdirs:
  sys.path.insert(0, os.path.abspath(os.path.join(currentdir, src)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment