Skip to content

sys.path does not understand pathlib Path objects #140672

@the-moog

Description

@the-moog

Bug report

Bug description:

It seems that despite pathlib being the cannonical means to express path like objects across all Python platforms, sys.path does not (always**) understand Path objects.

Example File Structure:

mydir/
    src/
        __init__.py
        mymod.py
    example/
       example.py

mymod.py

def hello():
    print("hello")

example.py - Results in an error

import sys
from pathlib import Path

my_src_dir = Path(__file__).parent.parent

sys.path.append(my_src_dir)

from src.mymod import hello

hello()

> python example.py

Traceback (most recent call last):
  File "/work/python/myapp/example/example.py", line 8, in <module>
    from src.mymod import hello                                                                                                                 ModuleNotFoundError: No module named 'src'           

If this code is changed to

example2.py

import sys
from pathlib import Path

my_src_dir = Path(__file__).parent.parent

# Note the addition of str()
sys.path.append(str(my_src_dir))

from src.mymod import hello

hello()
> python example.py
hello 

This behaviour goes against the 'Duck Typing' ethos that Python is built on.

** NOTE

Oddly this works correctly in Jupyter Notebooks without the str() hack

CPython versions tested on:

3.12

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions