Adding a directory to sys.path with pathlib

pathlib, python

Solution

From the docs:

A program is free to modify this list for its own purposes. Only strings should be added to `sys.path`; all other data types are ignored during import.

Add the path as a string to `sys.path`:

PROJECT_DIR = Path(__file__).parents[2]
sys.path.append(
    str(PROJECT_DIR / 'apps')
)

`PROJECT_DIR` is an instance of `PosixPath` which has all the goodies like `/` and `.parents` etc. You need to convert it to a `str`ing if you want to append it to `sys.path`.

Problem

I'm trying to add a directory to PATH with code like this: ``` PROJECT_DIR = Path(__file__).parents[2] sys.path.append( PROJECT_DIR / 'apps' ) ``` It doesn't work. If I do print `sys.path` I see something like this: ``` [..., PosixPath('/opt/project/apps')] ``` How should I fix this code? Is it normal to write `str(PROJECT_DIR / 'apps')`?

Original source