Simple example:
File structure is:
test/lib/f1.py
test/lib/f2.py
File contents:
$ cat lib/f1.py
from f2 import bar
def foo(a):
print(1+bar(a))
$ cat lib/f2.py
def bar(a):
return a
So f1.py
defines foo
, which relies on bar
, defined in f2.py
.
Now, loading f1.py
works just fine when inside test/lib/
:
$ python3
Python 3.5.2 (default, Nov 12 2018, 13:43:14)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from f1 import foo
>>> foo(1)
2
However, when loading from outside test/lib/
(say from test/
), this fails with an import error:
$ python3
Python 3.5.2 (default, Nov 12 2018, 13:43:14)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from lib.f1 import foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/tmp/pymod/lib/f1.py", line 1, in <module>
from f2 import bar
ImportError: No module named 'f2'
>>> Quit (core dumped)
Moving the code from f2.py
in f1.py
fixes the issue, but I don't want to do that.
Why am I getting this error and how can I avoid it?