0

I have a pytestlib package and modules as follows: test.py is simply creating module2 and the module2 imports module1. test.py code is working as expected if compiled and run directly in its own folder.

pyteslib\
    - __init__.py
    - module1.py
    - module2.py
    - test.py

module1.py

class Module1Class():
def __init__(self):
    self.msg ="This message is from Module1Class"

module2.py

from module1 import Module1Class

class Module2Class():
    def __init__(self):
        module1_obj = Module1Class()
        print(module1_obj.msg)

test.py

from module2 import Module2Class

module2_obj = Module2Class()

However; if I make this, a package, and import from another project I get an ImportModule error.

externaltest.py (In another project)

import sys

from pytestlib.module1 import Module1Class # No error importing module1
# from pytestlib.module2 import Module2Class # I have error if import module2


module1_obj = Module1Class()
# module2_obj = Module2Class() # I have error

I have this error:

Traceback (most recent call last):
  File "X:/SDK/python/testimp/imp.py", line 3, in <module>
    from pytestlib.module2 import Module2Class
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\pytestlib\module2.py", line 1, in <module>
    from module1 import Module1Class
ImportError: No module named 'module1'

In short, after making the package, module1 cannot be found by the module2.py of the package. But as you see, module1 can be directly imported by externaltest.py. Package cannot import its own module.

freewill
  • 1,111
  • 1
  • 10
  • 23

1 Answers1

0

Solution: use relative imports

from .module1 import ModuleClass1

Read this answer for a more complete explanation

Community
  • 1
  • 1
Vasil
  • 36,468
  • 26
  • 90
  • 114