3

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?

Rob
  • 3,333
  • 5
  • 28
  • 71

2 Answers2

1

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • then why does it work when foo is in the bar directory? Shouldn't it be doubling up the search for foo/foo/bar? – Rob Aug 15 '19 at 00:04
1

Assuming you are in the baz directory, you need to include your parent directory .. in the path. Then when you do from foo, the foo directory in your parent directory is found.

This works:

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

from foo import other

Read more:


Alternatively, since you included ../foo in the path, you could simply do import other, like so:

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

import other
Subhash
  • 3,121
  • 1
  • 19
  • 25