Nozdrum Nozdrum - 1 year ago 77
Python Question

Multiple relative Imports in python 3.5

This structure is just an example


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

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

from ..source import Foo

if __name__== "__main__":
f = Foo()

Now I want to run
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\", line 170, in _run_module_as_main
"__main__", mod_spec)
File "-\Python35\lib\", line 85, in _run_code
exec(code, run_globals)
File "~\test\", line 1, in <module>
from ..source import Foo
File "~\", 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 Source

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