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?
asked Jan 20, 2014 at 14:44
prosseekprosseek
180k211 gold badges564 silver badges866 bronze badges
11
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:
-
Then make sure to add add sources to your
PYTHONPATH
under:Preferences ~ Build, Execution, Deployment ~ Console ~ Python Console
- Now imports will be resolved:
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:
After all this don’t forget to restart. In PyCharm menu select: File –> Invalidate Caches / Restart
answered Jan 20, 2014 at 18:59
Games BrainiacGames Brainiac
79.6k33 gold badges140 silver badges199 bronze badges
16
- check for
__init__.py
file insrc
folder - add the
src
folder as a source root - Then make sure to add sources to your
PYTHONPATH
(see above) - in PyCharm menu select: File –> Invalidate Caches –> Restart
answered Jan 10, 2017 at 23:23
4
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
answered Apr 16, 2017 at 3:36
AeroHilAeroHil
8978 silver badges5 bronze badges
5
After testing all workarounds, i suggest you to take a look at Settings -> Project -> project dependencies
and re-arrange them.
answered Dec 12, 2016 at 13:03
mehdimehdi
2192 silver badges4 bronze badges
3
answered Jan 20, 2014 at 17:18
prosseekprosseek
180k211 gold badges564 silver badges866 bronze badges
3
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:
- close the project and quick PyCharm
- 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. - 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:
- Find the folder that relative imports require in the project explorer
- 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:
- Open PyCharm settings
- Navigate to Editor -> File Types
- Find Python and add
__init__.py
to the list of python files
or
- Find Text and delete
__init__.py
from the list of text files
answered Mar 19, 2021 at 0:46
OussOuss
2,7292 gold badges25 silver badges41 bronze badges
10
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.
answered Sep 29, 2021 at 17:13
bombenbomben
5906 silver badges16 bronze badges
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.
answered Mar 15, 2017 at 9:31
Ch_yCh_y
3461 gold badge4 silver badges16 bronze badges
1
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!
answered Dec 9, 2019 at 10:19
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.
answered Feb 17, 2018 at 14:38
danday74danday74
51.2k48 gold badges228 silver badges278 bronze badges
After following the accepted answer, doing the following solved it for me:
File
→ Settings
→ Project <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,0035 gold badges38 silver badges57 bronze badges
answered May 16, 2018 at 13:37
BenjaminBenjamin
4274 silver badges9 bronze badges
This worked for me: Top Menu -> File -> Invalidate Caches/Restart
answered Sep 4, 2019 at 17:34
- –> Right-click on the directory where your files are located in PyCharm
- Go to the –> Mark Directory as
- Select the –> Source Root
your problem will be solved
answered Jun 27, 2020 at 3:18
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.
answered Aug 17, 2020 at 9:24
TabsTabs
212 bronze badges
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).
answered Jun 26, 2016 at 8:28
kishs1991kishs1991
9494 gold badges10 silver badges16 bronze badges
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.
answered Apr 13, 2019 at 12:03
DanDan
4533 silver badges12 bronze badges
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.
answered Apr 24, 2020 at 8:59
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.
answered Jun 26, 2020 at 15:56
user2233949user2233949
2,00319 silver badges22 bronze badges
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.
answered Jan 25, 2021 at 22:01
PozinuxPozinux
9322 gold badges10 silver badges21 bronze badges
2
For me, adding virtualenv (venv
)’s site-packages path to the paths of the interpreter works.
Finally!
answered Jun 17, 2020 at 8:23
weamingweaming
5,3871 gold badge21 silver badges15 bronze badges
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.
answered Sep 9, 2021 at 23:55
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
answered May 4, 2022 at 2:47
1
This problem also appears if you use a dash within the Python filename, which therefore is strongly discouraged.
answered Sep 8, 2022 at 10:44
Greg HolstGreg Holst
8549 silver badges23 bronze badges
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
cUsers…AppDataRoamingPythonPython310site-packages
and copied it to the folder
C:Program FilesPython310Libsite-packages
After that, I reset pyCharm and that’s it!
answered Oct 10, 2022 at 12:40
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.
answered Dec 6, 2022 at 14:25
EstebanEsteban
1013 silver badges6 bronze badges
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
.
answered Dec 4, 2017 at 10:09
yunusyunus
2,3551 gold badge14 silver badges12 bronze badges
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 !!!
answered Nov 22, 2019 at 18:08
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’
answered Sep 18, 2019 at 7:36
Shravan KumarShravan Kumar
2411 gold badge3 silver badges6 bronze badges
0
I am using PyCharm to work on a project. The project is opened and configured with an interpreter, and can run successfully. The remote interpreter paths are mapped properly. This seems to be the correct configuration, but PyCharm is highlighting my valid code with “unresolved reference” errors, even for built-in Python functions. Why don’t these seem to be detected, even though the code runs? Is there any way to get PyCharm to recognize these correctly?
This specific instance of the problem is with a remote interpreter, but the problem appears on local interpreters as well.
davidism
120k29 gold badges385 silver badges336 bronze badges
asked Jul 30, 2012 at 16:23
James McCaldenJames McCalden
3,6462 gold badges15 silver badges18 bronze badges
1
File | Invalidate Caches… and restarting PyCharm helps.
answered Aug 2, 2012 at 8:12
Dmitry TrofimovDmitry Trofimov
7,3131 gold badge28 silver badges33 bronze badges
8
Dmitry’s response didn’t work for me.
I got mine working by going to Project Interpreters, Selecting the “Paths” tab, and hitting the refresh button in that submenu. It auto-populated with something called “python-skeletons”.
edit: screenshot using PyCharm 3.4.1 (it’s quite well hidden)
Ilian Iliev
3,2174 gold badges26 silver badges51 bronze badges
answered Nov 16, 2013 at 18:50
11
There are many solutions to this, some more convenient than others, and they don’t always work.
Here’s all you can try, going from ‘quick’ to ‘annoying’:
- Do
File
->Invalidate Caches / Restart
and restart PyCharm.- You could also do this after any of the below methods, just to be sure.
- First, check which interpreter you’re running:
Run
->Edit Configurations
->Configuration
->Python Interpreter
. - Refresh the paths of your interpreter:
File
->Settings
Project: [name]
->Project Interpreter
-> ‘Project Interpreter’: Gear icon ->More...
- Click the ‘Show paths’ button (bottom one)
- Click the ‘Refresh’ button (bottom one)
- Remove the interpreter and add it again:
File
->Settings
Project: [name]
->Project Interpreter
-> ‘Project Interpreter’: Gear icon ->More...
- Click the ‘Remove’ button
- Click the ‘Add’ button and re-add your interpeter
- Delete your project preferences
- Delete your project’s
.idea
folder - Close and re-open PyCharm
- Open your project from scratch
- Delete your project’s
- Delete your PyCharm user preferences (but back them up first).
~/.PyCharm50
on Mac%homepath%/.PyCharm50
on Windows
- Switch to another interpreter, then back again to the one you want.
- Create a new virtual environment, and switch to that environments’ interpreter.
- Create a new virtual environment in a new location — outside of your project folder — and switch to that environment’s interpreter.
- Switch to another interpreter altogether; don’t switch back.
If you are using Docker, take note:
- Make sure you are using
pip3
notpip
, especially with remote docker and docker-compose interpreters. - Avoid influencing
PYTHONPATH
. More info here: https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000058690-Module-not-found-in-PyCharm-but-externally-in-Python .
If the above did not work for you, but you did find another trick, then please leave a comment.
answered Mar 9, 2016 at 16:16
florislaflorisla
12.3k6 gold badges40 silver badges47 bronze badges
6
In my case it was the directories structure.
My project looks like this:
+---dir_A
+---dir_B
+app
|
-run.py
So right click on dir_b > “mark directory as” > “project root”
answered Feb 24, 2015 at 12:37
ShohamShoham
6,8948 gold badges40 silver badges40 bronze badges
4
You have to mark your root directory as:
SOURCE ROOT
(red),
and your applications:
EXCLUDED ROOT
(blue).
Then the unresolved reference will disappear. If you use PyChram pro it do this for you automatically.
dKen
3,0681 gold badge27 silver badges37 bronze badges
answered Jun 12, 2019 at 5:30
mujadmujad
6237 silver badges14 bronze badges
6
I find myself removing and re-adding the remote interpreter to fix this problem when Invalidating Caches or Refreshing Paths does not work.
I use vagrant and every once and awhile if I add a new VM to my multi-vm setup, the forwarded port changes and this seems to confuse PyCharm when it tries to use the wrong port for SSH. Changing the port doesn’t seem to help the broken references.
answered Mar 21, 2014 at 15:51
Thomas FarvourThomas Farvour
1,1032 gold badges11 silver badges24 bronze badges
0
If none of the other solutions work for you, try (backing up) and deleting your ~/.PyCharm40 folder, then reopening PyCharm. This will kill all your preferences as well.
On Mac you want to delete ~/Library/Caches/Pycharm40 and ~/Library/Preferences/PyCharm40.
And on Windows: C:Users$USER.PyCharm40.
answered Apr 16, 2015 at 3:51
ImranImran
12.8k8 gold badges62 silver badges79 bronze badges
1
Tested with PyCharm 4.0.6 (OSX 10.10.3)
following this steps:
- Click PyCharm menu.
- Select Project Interpreter.
- Select Gear icon.
- Select More button.
- Select Project Interpreter you are in.
- Select Directory Tree button.
- Select Reload list of paths.
Problem solved!
answered May 11, 2015 at 9:27
siripansiripan
1311 silver badge8 bronze badges
Sorry to bump this question, however I have an important update to make.
You may also want to revert your project interpreter to to Python 2.7.6 if you’re using any other version than that This worked for me on my Ubuntu installation of PyCharm 4.04 professional after none of the other recommendations solved my problem.
answered Jan 14, 2015 at 7:07
Fairlight EvonyFairlight Evony
2331 gold badge3 silver badges6 bronze badges
3
Much simpler action:
- File > Settings > Project > Project Interpreter
- Select “No interpreter” in the “Project interpreter” list
- Apply > Set your python interpreter again > Click Apply
Profit – Pycharm is updating skeletons and everything is fine.
answered Dec 26, 2019 at 13:25
1
If you want to ignore only some “unresolved reference” errors, you can also tell it PyCharm explicitly by placing this in front of your class/method/function:
# noinspection PyUnresolvedReferences
answered Dec 18, 2018 at 12:14
flixflix
1,62117 silver badges22 bronze badges
You might try closing Pycharm, deleting the .idea
folder from your project, then starting Pycharm again and recreating the project. This worked for me whereas invalidating cache did not.
answered Dec 28, 2015 at 22:25
I finally got this working after none of the proposed solutions worked for me. I was playing with a django rest framework project and was using a virtualenv I had setup with it. I was able to get Pycharm fixed by marking the root folder as the sources root, but then django’s server would throw resolve exceptions. So one would work when the other wouldn’t and vice versa.
Ultimately I just had to mark the subfolder as the sources root in pycharm. So my structure was like this
-playground
-env
-playground
That second playground folder is the one I had to mark as the sources root for everything to work as expected. That didn’t present any issues for my scenario so it was a workable solution.
Just thought I’d share in case someone else can use it.
answered Apr 12, 2016 at 23:10
user2233949user2233949
2,00319 silver badges22 bronze badges
It could also be a python version issue. I had to pick the right one to make it work.
answered May 14, 2016 at 19:47
ShehaazShehaaz
7531 gold badge7 silver badges12 bronze badges
None of the answers solved my problem.
What did it for me was switching environments and going back to the same environment. File->Settings->Project interpreter
I am using conda environments.
answered Jul 30, 2019 at 19:59
kkicakkica
4,0041 gold badge20 silver badges40 bronze badges
Mine got resolved by checking inherit global site-packages in PyCharm
File -> Settings -> Project Interpreter -> Add Local Interpreter -> Inherit global site-packages
answered Sep 5, 2022 at 21:55
0
I closed all the other projects and run my required project in isolation in Pycharm. I created a separate virtualenv from pycharm and added all the required modules in it by using pip. I added this virtual environment in project’s interpreter. This solved my problem.
answered Apr 1, 2016 at 10:25
Waqar DethoWaqar Detho
1,50218 silver badges17 bronze badges
Geeze what a nightmare, my amalgamation of different StackOVerflow answers:
- Switch to local interpreter /usr/bin/pythonX.X and apply
- View paths like above answer
- Find skeletons path. Mine was (/home/tim/Desktop/pycharm-community-2016.2.3/helpers/python-skeletons)
- Switch back to virt interpreter and add the skeletons path manually if it didn’t automatically show up.
answered Oct 12, 2016 at 9:02
TimTim
2841 gold badge4 silver badges20 bronze badges
None of the above solutions worked for me!
If you are using virtual environment for your project make sure to apply the python.exe
file that is inside your virtual environment directory as interpreter for the project (Alt + Ctrl + Shift + S)
this solved the issue for me.
answered Mar 22, 2017 at 12:46
Ali SherafatAli Sherafat
3,4161 gold badge36 silver badges50 bronze badges
In my case the inspection error shows up due to a very specific case of python code.
A min function that contains two numpy functions and two list accesses makes my code inspection give this kind of errors.
Removing the ‘d=0’ line in the following example gives an unresolved reference error as expected, but readding doesn’t make the error go away for the code inspector. I can still execute the code without problems afterwards.
import numpy as np
def strange(S, T, U, V):
d = 0
print min(np.abs(S[d]), np.abs(T[d]), U[d], V[d])
Clearing caches and reloading list of paths doesn’t work. Only altering the code with one of the following example patches does work:
- Another ordering of the ‘min’ parameters: schematically S U T V but not S T U V or T S U V
- Using a method instead of the function: S[d].abs() instead of np.abs(S[d])
- Using the built-in abs() function
- Adding a number to a parameter of choice: U[d] + 0.
answered Dec 21, 2017 at 13:20
My problem is that Flask-WTF is not resolved by PyCharm. I have tried to re-install and then install or Invalidate Cache and Restart PyCharm, but it’s still not working.
Then I came up with this solution and it works perfectly for me.
- Open Project Interpreter by Ctrl+Alt+S (Windows) and then click Install (+) a new packgage.
- Type the package which is not resolved by PyCharm and then click Install Package. Then click OK.
Now, you’ll see your library has been resolved.
answered Mar 19, 2020 at 12:48
In PyCharm 2020.1.4 (Community Edition) on Windows 10 10.0. Under Settings in PyCharm: File > Settings > Project Structure
I made two changes in Project Structure:
main folder marked as source and
odoo folder with all applications I excluded
Screenshot shows what I did.
After that I restarted PyCharm: File > Invalidate Caches / Restart…
Unresolved references error was removed
answered Jul 26, 2020 at 11:05
Invalidating the cache as suggested by other answers did not work for me. What I found to be the problem in my case was that PyCharm was marking init.py files of Python packages as text and thus not including them in the analysis which means python resolving was not working correctly.
The solution for me was to:
Open PyCharm settings
Navigate to Editor -> File Types
Find Python and add __init__.py
to the list of python files
or Find Text and delete __init__.py
from the list of text files
answered Mar 19, 2021 at 2:18
OussOuss
2,7292 gold badges25 silver badges41 bronze badges
To add yet another one: None of the solutions involving the Python Interpreter tab helped, however, I noticed I had to set Project Dependencies: In the project that had unresolved reference
errors, none of the dependencies were checked. Once I checked them, the relevant errors disappeared. I don’t know why some are checked to begin with and others are not.
answered Aug 5, 2022 at 17:26
If you are using vagrant
the error can be caused by wrong python interpreter.
In our vagrant
we are using pyenv
so I had to change Python Interpreter path
path from /usr/bin/python
to /home/vagrant/.pyenv/versions/vagrant/bin/python
answered Sep 3, 2018 at 12:28
DanilDanil
4,6931 gold badge35 silver badges49 bronze badges
I have a project where one file in src/
imports another file in the same directory. To get PyCharm to recognize I had to to go to File > Settings > Project > Project Structure > select src
folder and click “Mark as: Sources”
From https://www.jetbrains.com/help/pycharm/configuring-folders-within-a-content-root.html
Source roots contain the actual source files and resources. PyCharm uses the source roots as the starting point for resolving imports
answered Mar 7, 2020 at 22:45
qwrqwr
9,3055 gold badges57 silver badges101 bronze badges
I had to go to File->Invalidate Caches/Restart, reboot Ubuntu 18.04 LTS, then open Pycharm and File-> Invalidate Caches/Restart again before it cleared up.
answered Dec 15, 2020 at 5:41
For me it helped:
update your main directory “mark Directory as” -> “source root”
answered Jan 11, 2021 at 12:04
ValliValli
113 bronze badges
@kelorek works for me, but before, in interpereter paths I had to add some path.
lets say
from geometry_msgs.msg import Twist
is underline as error, then in remote machine in python run:
help("geometry_msgs")
at the end there will be path lets say :
/opt/ros/foxy/lib/python3.8/site-packages/geometry_msgs/__init__.py
so to Your intepreter pycharm path add
/opt/ros/foxy/lib/python3.8/site-packages
Hope it will help You and it helps me 🙂
answered Mar 2, 2021 at 0:36
AdrianAdrian
842 silver badges6 bronze badges
I had the same symptoms. In my instance the problem source was that I had set
idea.max.intellisense.filesize=50 in the custom properties.
I could resolve it by setting it to 100.
Help->Edit Custom Properties
answered May 5, 2021 at 8:19
NicoNico
731 silver badge8 bronze badges
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
Before fixing the unresolved reference issues, we must know why these issues occur in the first place.
An unresolved reference issue is raised in PyCharm IDE when:
- A variable is called/used outside the scope of its existence.
- A package is used within the code without prior installation or installed with an improper version.
- A function/class used within the code without importing it in the code or has an improper import path.
PyCharm highlights these areas where the code has the issue. Hover the mouse cursor over the highlighted area and PyCharm will display an Unresolved reference.
Let’s see some of the example scenarios of how the Unresolved reference issue occurs.
Issue 1: Using variables out of scope.
Unresolved reference: Variable out of scope
Fix: Declare the variable globally or use it only within the scope.
Fixed: Variable out-of-scope reference issue
Issue 2: Importing a package that has not been installed or does not have the required version containing that function/class.
Unresolved reference: package not installed
Fix: Install the package manually via the command line or click Install package <package-name> in the suggestion box. PyCharm will fetch and install the globally available packages in the current environment.
pip install flask
Fixed: Package installed to resolve the reference
Issue 3: Using a function that has not been imported properly in the current Python file.
File: other.py with hello() function
Unresolved reference: path to function is incorrect
Fix: Correct the line of import with the actual path to the hello() function.
Fixed: Unresolved function import
Disabling the warning altogether
You can also disable the Unresolved references warning completely by following these steps:
- Click on the File option in PyCharm’s menu bar.
File option
- Click on Settings.
Settings
- In the right pane of Settings go to Editor > Inspections.
Python drop-down
- Look for the Unresolved references option in the dropdown list and deselect the checkbox.
Deselect Unresolved references
- Click Apply button and PyCharm will disable showing the Unresolved references warning altogether.
Apply the changes
This is a part of PyCharm’s code Inspection feature, using which programmers can foresee the areas of code which may cause an issue during execution. PyCharm also suggests a quick resolution to most of these issues. This improves the agility of coding along with fewer errors.
Tip: Place the caret where the issue is and press the Alt+Enter shortcut to see the suggested fixes by PyCharm.
Last Updated :
30 Dec, 2022
Like Article
Save Article
PyCharm’s on-the-fly inspection immediately detects unresolved references, and highlights them with the red squiggly line. PyCharm suggests quick fixes to deal with the unresolved references in the source code.
Apply a quick-fix
-
Place the caret at an unresolved reference, PyCharm shows the red light bulb.
-
Click the bulb, or press Alt+Enter to reveal the list of available quick fixes:
PyCharm suggests a number of solutions. For example, choose one of the following options:
-
Import this name to add an import statement.
-
Create parameter to add a parameter with some initial value to the list of function parameters.
See also Extract parameter and Change signature.
-
Ignore unresolved reference <fully qualified symbol name>. The fully qualified name of the symbol will be added to the list of ignored references (File | Settings | Editor | Inspections – Python – Unresolved references).
-
Mark all attributes of <fully qualified type name> as ignored. In this case, the list of ignored references (File | Settings | Editor | Inspections – Python – Unresolved references) will be modified with the fully qualified name of the type with the wildcard (*) at the end.
Last modified: 06 March 2023
Введение
У меня есть проект Python в репозитории git. Все работает нормально для большинства членов команды, мы можем синхронизировать код и редактировать его без каких-либо проблем с Pycharm на разных платформах (Windows, Linux)
Проблема
На одном из компьютеров мы получаем “Unresolved reference” по всему коду почти для каждого импорта, за исключением встроенных в Python библиотек (т.е. импортирует datetime). На этом компьютере установлена версия Pycharm Mac.
Вопрос
Кто-нибудь знает, как это решить?, так как большая часть импорта не распознается завершением кода и навигацией через goto- > declare и т.д., не работает. Есть ли известная проблема с версией Mac?
Спасибо заранее!
Ответ 1
Ключ должен указывать исходный каталог в качестве корня источника. Попробуйте следующее:
- В представлении “Проект” щелкните правой кнопкой мыши исходный каталог Python
- В меню диалога выберите Отметить каталог как > Корень источника
Теперь папка должна быть синей, а не бежевой, чтобы указать, что это исходная папка Python.
Вы также можете настроить это в настройках PyCharm, выполнив следующее для проекта, который уже находится в PyCharm:
- На панели инструментов Mac выберите PyCharm > Настройки
- В открывшемся окне выберите Структура проекта в панели меню слева.
- Выберите проект в средней панели, если необходимо
- Щелкните правой кнопкой мыши на источнике Python в правой панели и выберите Источники в диалоговом окне меню
Ответ 2
У меня также была проблема, и мне потребовалось несколько часов, чтобы найти точное решение.
Вам нужно подтвердить следующее.
-
'django.contrib.staticfiles'
, добавляется вINSTALLED_APPS
в файлеsettings.py
вашего приложения. -
Каталог со статическим содержимым (например, изображениями) с именем
static
находится под корнем приложения.
Теперь выполните следующие действия
PyCharm > Настройки > Настройки проектa > Django
Убедитесь, что ваши Django Project root
, settings.py
и manage.py
script четко определены в диалоговом окне.
Вы хорошо пойдете.
Надеюсь это поможет.
Ответ 3
Я сделал все вышеперечисленное из einnocent и myildirim, но все равно должен был сделать следующее:
закрыть pycharm и вручную удалить папку .idea, это удалит все, что pycharm знает о коде.
открыть pycharm, reimport проект
комбинация установки правильного корня источника, перезапуск python с invalide cache и удаление папки .idea/реимпорт проекта pycharm исправили его для меня.
Ответ 4
Я столкнулся с аналогичной проблемой с pyspark (искра 2.1) и luigi.
Сбой попытки:
- Настройка переменной среды PYTHONPATH
- Недействительный кеш и перезапуск pycharm
- Отметьте каталог как Корень источника
Неразрешенная ссылка pyspark
может быть исправлена путем добавления каталога искрового питона в Content Root в проекте, но запуск проекта в качестве задачи luigi дал та же ошибка.
Успешные шаги
- Создайте пустой
__init__.py
файл в проекте -
Включите следующие строки кода вверху script
... import sys sys.path.append("/path/to/spark/python") sys.path.append("/path/to/spark/python/lib") ... // import pyspark files after above mentioned lines
и нерешенной проблемой ссылка ошибка была исправлена как в PyCharm и задачи LuiGi.
Ответ 5
Другой причиной может быть проектный интерпретатор. Например, если вы используете Python3.x, но интерпретатор предназначен для Python2.x. Вы можете проверить здесь:
Файл | Настройки | Проект: ‘projectname’ | Переводчик проекта
Ответ 6
PyCharm – Alt-F (ile); Настройки; Структура проекта; нажмите + добавить корневой контент;
укажите свою папку, содержащую пакет, в конфликте:/home/joker/anaconda3/envs/conda_py27/lib/python2.7/site-packages.
Я дополнительно отмечен как ресурсы (не уверен, что это обязательно). Нажмите “ОК”, и произойдет переиндексация.
Эта решила проблему для меня в PyCharm Professional 2016.2.3
Ответ 7
Моя десятка – Если вы работаете с виртуальными средами (у вас есть каталог venv
), убедитесь, что он помечен как исключенный.
Плагиат сверху:
- В представлении “Проект” щелкните правой кнопкой
venv
каталогvenv
- В диалоговом меню выберите Пометить каталог как > исключенный
Каталог должен стать оранжевым…
Это иногда случается, если вы сделали git clean
или по какой-то причине вам пришлось перестраивать вашу среду, а PyCharm не заметил