Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyCharm unresolved reference when importing class from other file

Tags:

python

pycharm

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?

like image 265
Iulian Avatar asked Apr 04 '15 22:04

Iulian


People also ask

How do I import classes into PyCharm?

PyCharm can do both. Type the name of the package and hit Alt-Enter , then choose Install and Import package . PyCharm will do both: you'll see a notification during the installation, then the import will be generated in the right way, according to your project styles.

How do I fix unresolved reference in Intellij?

The only way to resolve the behavior is to use the "Invalidate Caches / Restart... ->Invalidate and Restart" option.


2 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.

like image 59
yole Avatar answered Oct 21 '22 08:10

yole


If you are using python version 3 try this

from .pack import myclass

This worked for me

like image 44
kayleb Avatar answered Oct 21 '22 07:10

kayleb