1

My Python version is 3.5.

I have a project with structure like this:

-- test
---- __init__.py
---- one
------ __init__.py
------ first.py
---- two
------ __init__.py
------ second.py

Content of first.py file:

class FirstClass(object):

    def hello(self):
        return 'hello'

Content of second.py file:

def main():
    first = FirstClass()
    print(first.hello())

if __name__ == '__main__':
    main()

The problem is that I can't import FirstClass in second.py, I tried:

from test.one.first import FirstClass

Result:

Traceback (most recent call last):
  File "second.py", line 3, in <module>
    from test.one.first import FirstClass
ModuleNotFoundError: No module named 'test.one'

Also, I tried this approach:

from ..one.first import FirstClass

Result:

Traceback (most recent call last):
  File "second.py", line 3, in <module>
    from ..one.first import FirstClass
ValueError: attempted relative import beyond top-level package

So, my question is: how do to import in situations like this?

Tom
  • 787
  • 1
  • 12
  • 28
  • see: http://stackoverflow.com/questions/8706309/how-to-reference-to-the-top-level-module-in-python-inside-a-package – parsethis Feb 23 '17 at 04:34
  • Another related question: http://stackoverflow.com/questions/16981921/relative-imports-in-python-3 – Leon Feb 23 '17 at 04:46

1 Answers1

0

this is a hack but but would work:

def main():
    first = FirstClass()
    print(first.hello())

if __name__ == '__main__':
    from sys import path
    from os.path import dirname as dir

    path.append(dir(path[0]))
    __package__ = "one"
    from one.first import FirstClass
    main()

see: Leon's link in comment

parsethis
  • 7,998
  • 3
  • 29
  • 31