543

I have a directory structure

├── simulate.py
├── src
│   ├── networkAlgorithm.py
│   ├── ...

And I can access the network module with sys.path.insert().

import sys
import os.path
sys.path.insert(0, "./src")
from networkAlgorithm import *

However, pycharm complains that it cannot access the module. How can I teach pycham to resolve the reference?

enter image description here

prosseek
  • 182,215
  • 215
  • 566
  • 871
  • 7
    Do src folder has `__init__.py` file? – Puffin GDI Jan 20 '14 at 15:33
  • @Puffin GDI: No, it does not. – prosseek Jan 20 '14 at 15:44
  • 7
    @PuffinGDI Do src folders need this __init__.py file? – Jack Chi May 21 '16 at 03:38
  • Yes in order for python to identify packages: http://stackoverflow.com/questions/42094723/pycharm-marking-a-folder-as-sources-root-is-not-recursive-for-subfolders/ – rnoodle Feb 10 '17 at 16:48
  • I renamed the class name and continue working on it. When i hit run, there was this error, totally forgot renaming and tried looking for pycharm suggestions during import. Damn, suggestions are case sensitive! - New to python!! – Vignesh Paramasivam Apr 09 '19 at 18:01
  • how does this answer change if my library is installed in editable mode e.g. `pip install -e .`? – Charlie Parker Dec 13 '21 at 18:08
  • for me it seems that deleting the `.idea` folder fixed everything. See https://stackoverflow.com/a/66701106/1601580 – Charlie Parker Dec 13 '21 at 18:47
  • @PuffinGDI why does having the `__init__.py` matter? I believe I've not put them in the past and when I run code it still is able to find the other folders and packages inside of the main pkg folder. – Charlie Parker Dec 13 '21 at 19:06
  • @CharlieParker Why is the bounty on this question and not on your new question? Is this question the one you're trying to get answered (The one with an accepted answer with nearly 1000 upvotes) or is it your other one you want answered? Putting it here means I need to go through 25 answers, multiple posts, 8 years of answers, and it's not clear what I'm even trying to answer – nanotek Dec 14 '21 at 18:24
  • @nanotek I believe I have to wait 2 days before placing a bounty on new questions. I sympathize with you. The answers here didn't work for me. But to answer mine even with a bounty, wouldn't you need to go through lots of answers anyway? If you answer mine I promise to reward you if it works :) – Charlie Parker Dec 14 '21 at 18:29
  • one more thing to watch out is the name of the production code file. If you have hyphens (-) rather than underscores (_), test class will fail to import them. – Laksitha Ranasingha May 15 '22 at 23:09

29 Answers29

1128

Manually adding it as you have done is indeed one way of doing this, but there is a simpler method, and that is by simply telling pycharm that you want to add the src folder as a source root, and then adding the sources root to your python path.

This way, you don't have to hard code things into your interpreter's settings:

  • Add src as a source content root:

                            enter image description here

  • Then make sure to add add sources to your PYTHONPATH under:

    Preferences ~ Build, Execution, Deployment ~ Console ~ Python Console
    

enter image description here

  • Now imports will be resolved:

                      enter image description here

This way, you can add whatever you want as a source root, and things will simply work. If you unmarked it as a source root however, you will get an error:

                                  enter image description here

After all this don't forget to restart. In PyCharm menu select: File --> Invalidate Caches / Restart

Alan W. Smith
  • 24,647
  • 4
  • 70
  • 96
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
  • 25
    This also works if you're using the Python plugin with IntelliJ. – rob mayoff Feb 27 '14 at 00:56
  • 20
    This solution works. The problem of it is that when another programmer retrieves the code from svn, she has to do the same settings again to get rid of the "unresolved reference" error prompt. – Ben Lin Mar 20 '14 at 18:00
  • @BenLin True, however for all other solutions you would have to do the same. – Games Brainiac Mar 20 '14 at 22:19
  • 3
    @GamesBrainiac, the solution is that the IDE can parse "sys.path.insert(0, "./src")" add that into PYTHONPATH for this specific file, then give proper syntax analysis. – Ben Lin Mar 21 '14 at 16:33
  • 3
    You also need to make sure your content root path is correct. In pycharm 5 you can find this in Preferences -> Project -> Project Structure. – lps Nov 24 '15 at 18:18
  • 1
    Strangely, sub-directories are not taken into account. For example, if under `src`, we have `views` folder inside which I have `myview.py`, I still receive unresolved reference error when trying `from src.views.myview import `... – SexyBeast Jun 02 '16 at 22:47
  • Just for the record: if you're using django, the root folder should be that one named `projectName` with the `manage.py` inside (not that one with virtual env etc.) – thicolares Apr 30 '17 at 16:10
  • 1
    I had to make my "trunk" folder (in SVN) the Source Root. Then it worked for me. When I tried the folder above that; it didn't work for some odd reason. – Joe Dec 04 '17 at 18:42
  • This works great. I just had to add multiple folders as source route. thanks – Aqib Mumtaz May 15 '18 at 07:36
  • The solution provided by @robmayoff works, too. Installed Python plugins and the issue has gone away. Thanks – 27P Sep 06 '18 at 11:00
  • In `IntelliJ IDEA 2016+` this option has been relocated; see [**@AeroHil**'s answer](https://stackoverflow.com/a/43433438/3679900) – y2k-shubham Oct 03 '18 at 07:11
  • What is the difference if you do the second step of adding sources to PYTHONPATH or not? Are both step 1 (add src as source content root) and step 2 (add sources to PYTHONPATH) necessary under all circumstances? – Gandalf Saxe Dec 27 '18 at 22:58
  • why was this a problem? – Stéphane Bruckert Oct 31 '20 at 22:46
  • how does this answer change if my library is installed in editable mode e.g. `pip install -e .`? – Charlie Parker Dec 13 '21 at 18:08
  • 1
    for me it seems that deleting the `.idea` folder fixed everything. See https://stackoverflow.com/a/66701106/1601580 – Charlie Parker Dec 13 '21 at 18:47
  • my `PYTHONPATH ` is empty, is that normal? – Charlie Parker Dec 13 '21 at 22:09
74
  1. check for __init__.py file in src folder
  2. add the src folder as a source root
  3. Then make sure to add sources to your PYTHONPATH (see above)
  4. in PyCharm menu select: File --> Invalidate Caches --> Restart
amin arghavani
  • 1,883
  • 14
  • 21
Ukr
  • 2,411
  • 18
  • 16
35

If anyone is still looking at this, the accepted answer still works for PyCharm 2016.3 when I tried it. The UI might have changed, but the options are still the same.

ie. Right click on your root folder --> 'Mark Directory As' --> Source Root

AeroHil
  • 937
  • 8
  • 5
22

After testing all workarounds, i suggest you to take a look at Settings -> Project -> project dependencies and re-arrange them.

pycharm prefrence

mehdi
  • 229
  • 2
  • 4
15

Normally, $PYTHONPATH is used to teach python interpreter to find necessary modules. PyCharm needs to add the path in Preference.

enter image description here

prosseek
  • 182,215
  • 215
  • 566
  • 871
9

There are several reasons why this could be happening. Below are several steps that fixes the majority of those cases:

.idea caching issue

Some .idea issue causing the IDE to show error while the code still runs correctly. Solution:

  1. close the project and quick PyCharm
  2. delete the .idea folder where the project is. note that it is a hidden folder and you might not be aware of its existence in your project directory.
  3. start PyCharm and recreate the project

imports relative not to project folder

Relative imports while code root folder is not the same as the project folder. Solution:

  1. Find the folder that relative imports require in the project explorer
  2. right click and mark it as "Source Root"

Editor not marking init.py as Python but as Text

Which is the most illusive of all the cases. Here, for some reason, PyCharm considers all __init__.py files not to be python files, and thus ignores them during code analysis. To fix this:

  1. Open PyCharm settings
  2. Navigate to Editor -> File Types
  3. Find Python and add __init__.py to the list of python files

or

  1. Find Text and delete __init__.py from the list of text files
Ouss
  • 2,912
  • 2
  • 25
  • 45
  • how do I find the `.idea` folder? – Charlie Parker Dec 13 '21 at 18:41
  • Answering my own question, I went to the root of my project (not src but say the git repo root folder). Then I did `rm -rf .idea`. Then restarted pycharm. I really puzzled why this worked...so far. At least the ide is finding the files and the running of the code does too (but that always worked even when running from within pycharm e.g. with the debugger). – Charlie Parker Dec 13 '21 at 18:45
  • why does this work? – Charlie Parker Dec 13 '21 at 18:47
  • btw, is recreating the project really necessary? – Charlie Parker Dec 13 '21 at 19:05
  • Recreating the project happens automatically when starting PyCharm in that folder. That will re-creates the .idea folder that stores project settings, the string search index and other things. – Ouss Dec 13 '21 at 19:10
  • To find the `.idea` folder use `ls -a` to list all files and folders including hidden one (that start with a dot). To see the content of the .idea folder you can use the terminal to `cd` into it the `ls` as usual. – Ouss Dec 13 '21 at 19:13
  • Why does refreshing the cache works for you? Well it could be that the cache is outdated and because of some glitch in PyCharm or some change you made to the project, the cache was not refreshed and functions and classes and packages names lookup table was not refreshed. When running the code, Python interpret your code in real time (almost) and that part has nothing to do with PyCharm. PyCharm is just a fancy text editor in this case. – Ouss Dec 13 '21 at 19:17
  • Anyway I am happy recreating the .idea folder worked for you…! – Ouss Dec 13 '21 at 19:18
  • Hi Ouss, thanks for your kind replies. It is sad, it actually doesn't work consistently for some reason :(. Now that I changed file in my project it cannot find the reference to the projects source root `src`. So I am puzzled why it's not working. It has worked with other laptops out of the box as long as I activate the conda env. Might it be that? I also had some issues earlier with the `PATH` env variable so I wonder if it's that. – Charlie Parker Dec 13 '21 at 22:02
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/240111/discussion-between-charlie-parker-and-ouss). – Charlie Parker Dec 13 '21 at 22:10
7

The project I cloned had a directory called modules and was successfully using files from there in the code with import this as that, but Pycharm was unable to jump to those code fragments because it did not recognise the imports.

Marking the module folder in the following settings section as source solved the issue.

Pycharm Preferences

bomben
  • 590
  • 6
  • 16
5

Generally, this is a missing package problem, just place the caret at the unresolved reference and press Alt+Enter to reveal the options, then you should know how to solve it.

Ch_y
  • 356
  • 1
  • 4
  • 16
5

Although all the answers are really helpful, there's one tiny piece of information that should be explained explicitly:

  • Essentially, a project with multiple hierarchical directories work as a package with some attributes.
  • To import custom local created Classes, we need to navigate to the directory containing .py file and create an __init__.py (empty) file there.

Why this helps is because this file is required to make Python treat the directory as containing packages. Cheers!

Waqas Kayani
  • 133
  • 2
  • 9
3

Install via PyCharm (works with Community Edition). Open up Settings > Project > Project Interpreter then click the green + icon in the screenshot below. In the 2nd dialogue that opens, enter the package name and click the 'Install Package' button.

enter image description here

danday74
  • 52,471
  • 49
  • 232
  • 283
3

After following the accepted answer, doing the following solved it for me:

FileSettingsProject <your directory/project>Project Dependencies

Chose the directory/project where your file that has unresolved imports resides and check the box to tell Pycharm that that project depends on your other project.

My folder hierarcy is slightly different from the one in the question. Mine is like this

├── MyDirectory  
│     └── simulate.py  
├── src  
│     ├── networkAlgorithm.py  
│     ├── ...

Telling Pycharm that src depends on MyDirectory solved the issue for me!

Neuron
  • 5,141
  • 5
  • 38
  • 59
Benjamin
  • 437
  • 4
  • 9
2

Many a times what happens is that the plugin is not installed. e.g.

If you are developing a django project and you do not have django plugin installed in pyCharm, it says error 'unresolved reference'. Refer: https://www.jetbrains.com/pycharm/help/resolving-references.html

Ranjeet
  • 393
  • 2
  • 10
2

This worked for me: Top Menu -> File -> Invalidate Caches/Restart

Gershon Herczeg
  • 3,016
  • 23
  • 33
2
  1. --> Right-click on the directory where your files are located in PyCharm
  2. Go to the --> Mark Directory as
  3. Select the --> Source Root

your problem will be solved

2

I was also using a virtual environment like Dan above, however I was able to add an interpreter in the existing environment, therefore not needing to inherit global site packages and therefore undo what a virtual environment is trying to achieve.

Tabs
  • 21
  • 2
1

Please check if you are using the right interpreter that you are supposed to. I was getting error "unresolved reference 'django' " to solve this I changed Project Interpreter (Changed Python 3 to Python 2.7) from project settings: Select Project, go to File -> Settings -> Project: -> Project Interpreter -> Brows and Select correct version or Interpreter (e.g /usr/bin/python2.7).

kishs1991
  • 969
  • 4
  • 10
  • 16
1

In my case the problem was I was using Virtual environment which didn't have access to global site-packages. Thus, the interpreter was not aware of the newly installed packages.

To resolve the issue, just edit or recreate your virtual interpreter and tick the Inherit global site-packages option.

enter image description here

Dan
  • 473
  • 3
  • 13
  • Doesnt this have undesirable consequences and defeat one reason to use a virtual environement? That is, if you take that environment somewhere and those global site-packages are installed, then you are in trouble. Thats what i thought. – theStud54 Oct 22 '19 at 19:55
1

Done in PyCharm 2019.3.1 Right-click on your src folder -> "Mark Directory as" -> Click-on "Excluded" and your src folder should be blue.

1

I tried everything here twice and even more. I finally solved it doing something I hadn't seen anywhere online. If you go to Settings>Editor>File Types there is an 'Ignore Files and folders' line at the bottom. In my case, I was ignoring 'venv', which is what I always name my virtual environments. So I removed venv; from the list of directories to ignore and VOILA!! I was FINALLY able to fix this problem. Literally all of my import problems were fixed for the project.

BTW, I had installed each and every package using PyCharm, and not through a terminal. (Meaning, by going to Settings>Interpreter...). I had invalidated cache, changed 'Source Root', restarted PyCharm, refreshed my interpreters paths, changed interpreters, deleted my venv... I tried everything. This finally worked. Obviously there are multiple problems going on here with different people, so this may not work for you, but it's definitely worth a shot if nothing else has worked, and easy to reverse if it doesn't.

user2233949
  • 2,053
  • 19
  • 22
1

For my case :

Directory0
    ├── Directory1
    │     └── file1.py  
    ├── Directory2
    │     ├── file2.py  

Into file1, I have :

from Directory2 import file2

which trows an "unresolved reference Directory2".

I resolved it by:

  • marking the parent directory Directory0 as "Source Root" like said above

AND

  • putting my cursor on another line on the file where I had the error so that it takes my modification into account

It is silly but if I don't do the second action, the error still appears and can make you think that you didn't resolve the issue by marking the parent directory as Source Root.

Pozinux
  • 964
  • 2
  • 10
  • 22
0

For me, adding virtualenv (venv)'s site-packages path to the paths of the interpreter works. Finally!

enter image description here

weaming
  • 5,605
  • 1
  • 23
  • 15
0

I had the same problem and also try so many suggestions but none of them worked, until I find this post (https://stackoverflow.com/a/62632870/16863617). Regardless his solution didn't work for me, it helped me to came up with the idea to add _init.py_ into the --> Settings | Editor | File Types | Python | Registered patterns

ScreenShot

And the unresolved reference error is now solved.

0

just note if u have a problem with python interpreter not installing packages, just change the permission for folder PycharmProjects C:\Users'username'\PycharmProjects to every one

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 04 '22 at 22:03
0

This problem also appears if you use a dash within the Python filename, which therefore is strongly discouraged.

Greg Holst
  • 874
  • 10
  • 23
0

I encountered an import problem when installing aiogram. At the same time, the bot worked, but pyCharm highlighted the import in red and did not give hints. I've tried all of the above many times.As a result, the following helped me: I found the aiogram folder at the following path c\Users...\AppData\Roaming\Python\Python310\site-packages and copied it to the folder C:\Program Files\Python310\Lib\site-packages After that, I reset pyCharm and that's it!

0

In my case, with Pycharm 2019.3, the problem was that I forgot to add the extension '.py' to the file I wanted to import. Once added, the error went away without needing to invalides caches or any other step.

Esteban
  • 101
  • 3
  • 6
-1

Pycharm uses venv. In the venv's console you should install the packages explicitly or go in settings -> project interpreter -> add interpreter -> inherit global site-packages.

yunus
  • 2,445
  • 1
  • 14
  • 12
-1

The easiest way to fix it is by doing the following in your pyCharm software:

Click on: File > Settings > (Project: your project name) > Project Interpreter >

then click on the "+" icon on the right side to search for the package you want and install it.

Enjoy coding !!!

  • 1
    Welcome to Stack Overflow, and thanks for your answer. Whilst this may be correct, in the future please avoid posting images or links to other sites without context or further details. The link may stop working at some point, making this answer less useful for other users. – Foxocube Nov 22 '19 at 18:14
  • @CyberJacob Thank you very much, and thanks a lot for your advice, I've edited the answer by removing the image and adding text instead. – zaid.mohammed Nov 22 '19 at 23:01
-2

In newer versions of pycharm u can do simply by right clicking on the directory or python package from which you want to import a file, then click on 'Mark Directory As' -> 'Sources Root'

Shravan Kumar
  • 241
  • 1
  • 3
  • 6