Nozdrum Nozdrum - 2 months ago 14
Python Question

Multiple relative Imports in python 3.5

This structure is just an example

pkg\
test\
__init__.py
test.py
__init__.py
source.py
another_source.py


another_source.py

class Bar():
def __init__(self):
self.name = "bar"


source.py

from another_source import Bar
class Foo():
def __init__(self):
self.name = "foo"
b = Bar()


test.py

from ..source import Foo

if __name__== "__main__":
f = Foo()
print(f.name)


Now I want to run test.py.
As it has been accepted as the answer I have to go above my current package and run

python -m pkg.test.test


But this does not work and python gives me a traceback

Traceback (most recent call last):
File "-\Python35\lib\runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "-\Python35\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "~\test\test.py", line 1, in <module>
from ..source import Foo
File "~\source.py", line 1, in <module>
from another_source import Bar
ImportError: No module named 'another_source'


If I remove all the another_source-stuff it will work, but that is not a solution.

Now is there a sane way to import classes from places that are one directory above me?

Answer

pkg.source is trying to import things from the pkg.another_source module as if it were top-level. That import needs to be corrected:

from .another_source import Bar
# or
from pkg.another_source import another_source