PyDev.Debugger icon indicating copy to clipboard operation
PyDev.Debugger copied to clipboard

Directory containing file unconditionally appended to sys.path

Open apmorton opened this issue 6 months ago • 0 comments

Consider the following project layout:

├── bar
│   ├── __init__.py
│   └── thing.py
└── foo
    ├── bar.py
    ├── __init__.py
    └── script.py

All files are empty except foo/script.py, which simply contains import bar.thing. The directory containing foo is added to the PYTHONPATH environment variable globally.

$ env PYTHONPATH=. python foo/script.py
Traceback (most recent call last):
  File "/foo/script.py", line 1, in <module>
    import bar.thing
ModuleNotFoundError: No module named 'bar.thing'; 'bar' is not a package

This is expected, since foo/bar.py shadows bar/thing.py due to python adding the directory of the invoked file to sys.path.

Python 3.11 adds PYTHONSAFEPATH and -P options to address this issue.

$ env PYTHONPATH=. python -P foo/script.py
# no import error
$ env PYTHONPATH=. PYTHONSAFEPATH=1 python foo/script.py
# no import error

However, when running under pydevd.py, the same is not true because of the following lines: https://github.com/fabioz/PyDev.Debugger/blob/pydev_debugger_3_0_3/pydevd.py#L2584-L2589

If you configure pycharm to run your script with PYTHONSAFEPATH=1 pydevd.py will still unconditionally prepend the scripts directory and you will get the import failure when debugging.

apmorton avatar Feb 01 '24 22:02 apmorton