Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does python look if your sys.path uses relative directory?

Tags:

python

sys

I have a project like:

project/
    foo/
       other.py
    bar/
       baz.py

If I code something like:

import sys
sys.path.insert(0, '../foo')

from foo import other

It doesn't work. But if I move foo into the bar directory it works. I realize this is bad code style, but how is this relative path searched and where does the documentation define it?

like image 342
Rob Avatar asked Jan 21 '26 02:01

Rob


1 Answers

from foo import other will append foo to each of the directories in sys.path. So it's looking for ../foo/foo/other.py, but the actual path is just ../foo/other.py.

You should just insert .. into sys.path, then it will look for ../foo/other.py. Or if you only want to include that directory in the path, just use import other, without from foo.

like image 132
Barmar Avatar answered Jan 22 '26 15:01

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!