Skip to content

Instantly share code, notes, and snippets.

@berkorbay
Created January 19, 2023 14:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save berkorbay/0b98b0b56361b3a364f332d504e6ed8f to your computer and use it in GitHub Desktop.
Save berkorbay/0b98b0b56361b3a364f332d504e6ed8f to your computer and use it in GitHub Desktop.
Relative import methods in Python
  1. Best way is editable pip packages (reference)

pip install --editable /path/to/package

You need to include a minimal setup.py

from setuptools import setup, find_packages

setup(
    name="packagename",
    version="1.0",
    author="[AUTHORNAME]",
    description="[DESCRIPTION]",
    packages=find_packages(),
)

p.s. It is also possible to use repositories as editable (thanks chatGPT)

pip install --editable git+https://github.com/user/repo.git#egg=package

  1. sys.path method
import os
import sys
#### Include upper dirs start
dpath = os.path.dirname(os.path.abspath(__file__))
for i in range(1): ## For more than one level of folders you can increase this number
    dpath = os.path.dirname(dpath)
sys.path.insert(1, dpath)
#### Include upper dirs end
  1. Set a PYTHONPATH (I never tried this one)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment