1

./package/test.py is working smoothly. I am expecting ./test.py would work smoothly just like that, but I am getting this running ./test.py:

Traceback (most recent call last):
  File "test.py", line 2, in <module>
    from package.subclass import Subclass
  File ".../package/subclass.py", line 1, in <module>
    from subclass import Subclass
ModuleNotFoundError: No module named 'subclass'

It is able to import class1. When it reads the 1st line of the subclass, it gives ModuleNotFoundError. I have tried with ./package/__init__.py, a empty one gives the same error as above. When I have proper imports in ./package/__init__.py, the error becomes not being able to even find class1 in line 1 of __init__.py.

File directory as below:

./package/class1.py
./package/class2.py
./package/subclass.py
./package/test.py
./test.py

Code:

# ./package/class1.py
class Class1():
...

# ./package/class2.py
class Class2():
...


# ./package/subclass.py
from class2 import Class2
class Subclass(Class2):
...

# ./package/test.py
from class1 import Class1
from subclass import Subclass
...

# ./test.py
from package.class1 import Class1
from package.subclass import Subclass
...
Sara Takaya
  • 298
  • 2
  • 17

3 Answers3

2

Setting PYTHONPATH could be an option. Alternatively, given your current structure:

#subclass.py
from .class2 import Class2

class Subclass(Class2):
    pass

#package/test.py
from .class1 import Class1
from .subclass import Subclass

#test.py
from package.class1 import Class1
from package.subclass import Subclass

To run test.py, simply run python test.py or python -m test To run package/test.py, you will have to use python -m package.test

ksha
  • 2,007
  • 1
  • 19
  • 22
0

Try adding an empty __init__.py to the directory

The __init__.py tells the python interpreter that the directory it is dealing with is actually a module.

Hope this helps!

Ishan Joshi
  • 487
  • 3
  • 7
0

Aside from proper __init__.py, you'll also need to use:

from package.class1 import Class1
from package.subclass import Subclass

Note the added package.. Just a dot would also work, as that would be a relative import.

Gloweye
  • 1,294
  • 10
  • 20