Skip to content
Advertisement

What is the correct way to import this class?

I have the following repository structure:

directoryA
    - moduleA.py (it contains MyClass class)
directoryB
    - moduleB.py

In moduleB.py I need to import MyClass, I use the following command:

from directoryA.moduleA import MyClass

When I run the main() function in moduleB.py I have the following error:

ModuleNotFoundError: No module named ‘directoryA’

I run the moduleB.py from directoryB in the following way:

py moduleB.py

How could I fix this problem?

Advertisement

Answer

The best you can do to organizing your scripts would be using a file called main.py in the main folder, which must be in the same directory as directoryA and directoryB.

In main.py, just import the files from child directories:

from directoryA.moduleA import MyClass
import directoryB.moduleB

# Do whatever you want, but sometimes, just don't go too overboard.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement