Skip to content
Advertisement

PyCharm unresolved reference when importing class from other file

This problem has been driving me nuts. I am trying to import a class from a file in the same directory. PyCharm is giving me the “Unresolved reference” error. MyClass is defined in file.py.

Unresolved reference

I have found these questions:

I have the following project structure:

Project structure

I have marked src as the sources root…

I have set the “Add source roots to PYTHONPATH”:

Add sources option

I have tried File -> Invalidate Caches / Restart.. (I even restarted the computer).

If I try to run it, I get the following error in the console: ImportError: cannot import name 'MyClass'

The interpreter is a virtualenv on Python 3.4 on Ubuntu x64 14.04.

If I install and import any 3rd party packages, they work fine.

If I try echo $PYTHONPATH in the terminal it returns nothing (same with env | grep PYTHONPATH. I have the appropriate virtualenv active when I try these.

Any clues?

Advertisement

Answer

If MyClass is defined in pack/file.py, you need to import it as:

from pack.file import MyClass

Note that using names of Python built-in types (such as file) for your own modules is a bad idea.

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