Answer a question

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:

  • Unresolved reference issue in PyCharm
  • Pycharm: "unresolved reference" error on the IDE when opening a working project
  • PyCharm shows unresolved references error for valid code
  • Unresolved reference when importing from sibling sub-package with

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?

Answers

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.

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐