"No module named MyClass" error on PyCharm

2.5k views Asked by At

I am using PyCharm Community Edition 2016.3.1 but when I have two+ python files on the same directory, if I import one of them into the other it gets underlined saying:

# main.py
import MyClass1

No module named MyClass1 less... (Ctrl+F1) This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level items are supported better than instance items.

but when I execute my main.py it works properly.

Other regular imports like import sys don't get underlined.

2

There are 2 answers

0
afxentios On BEST ANSWER

If those two python files are under the same directory eg. MyDirectory, you need to import the classes using the MyDirectory as the root. So for example if you have the below project structure:

└── MyDirectory
    ├── file1.py (MyClass1)
    └── file2.py (MyClass2)

To import the MyClass1 into the file2.py you can do it as below:

from MyDirectory.file1 import MyClass1
0
SudoKid On

The reason you are getting this error is because you are not importing correctly.

Python imports follow this syntax.

import filename

This means you need to have a file name filename.py in the current directory. You can also import a specific class from that file like so.

from filename import MyCalss