Python unresolved reference google

PyCharm unresolved reference on import?

I don’t get the error underline in PyCharm, but when running my app from terminal, I get this error: ModuleNotFoundError: No module named ‘__main__.oauth2_helper’; ‘__main__’ is not a package What do you think, why is this happening?

Did you select the directory you run your app from terminal as the Sources Root ? (Right click on the folder you want to be the root and click Mark Directory As -> Sources Root ) The Root folder should have a blue icon. Then PyCharm will autocheck the imports from this defined root.

1 Answer 1

There are two things at play, here:

Like Eskapp says in the comment, PyCharm is configured to a different Project Root than you seem to expect, as evidenced by it marking your imports as unresolved references. You didn’t provide any hints to your project structure, but its likely that your Project Root is set to the parent directory of your Python module (or even further up the hierarchy). PyCharm is looking for $/oath2_helper and isn’t finding it, because Project Root is set to the wrong directory.

You then try to fix this problem by changing to relative imports, which seems like a logical solution. It looks like you’re directly calling the module in which those imports are written (i.e. python myapp.py ). When you call a module in this way, it drops information about the package structure, and no longer has any information about where other modules are relatively located. See https://stackoverflow.com/a/73149/11034626

Читайте также:  Img set size css

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Unresolved reference in Django’s docstring in PyCharm

I use Google Style Python Docstrings like in this Example for my Django’s project. When i create a class and using an attributes notation in docstring, Pycharm always say — «Unresolved reference».

class Post(models.Model): """ Class for posts. Attributes: title(str): Post title. """ title = models.CharField(max_length=120) 

I understand that PyCharm doesn’t see self for title and def __init__() function and write this error, but in Django I’ve never seen using def __init__() for classes inherited from models . What should I do? Is this my error or does PyCharm not see context in this case? Should I use def __init__() or something else or write docsting in another way?

You can ignore that kind of errors with Django or create an issue in youtrack to support this feature. I guess it’s not implemented in pycharm professional.

3 Answers 3

PyCharm does not appear to have support for this currently. The active issue for this in JetBrains issue tracker is https://youtrack.jetbrains.com/issue/PY-16760, please consider upvoting it to get it fixed. The only workaround if you want to avoid seeing these «Unresolved reference» errors in your docstrings is to disable the inspection in Preferences > Editor > Inspections > Unresolved references.

Another option that I have tried in the past is removing the «Attributes:» header and writing my attribute documentation on the same indentation level as the rest of the docstring. This no longer gives you a warning, but you are no longer conforming 100% to the Google Docstring Style Guide.

Источник

Why does PyCharm give unresolved reference errors on some Numpy imports?

The reason you are getting this is because of PyCharm’s static analysis. Now, what Python does is use static skeletons (some are pre-generated and some are generated) to give you the analysis. Take a look at the pre-generated skeletons here -> https://github.com/JetBrains/python-skeletons

This might be solved, by enabling the following:

enter image description here

However, if that does not work:

enter image description here

which will block off the error, it will appear as a comment above the line.

-1 for not mentioning where the setting can be found. Go to File -> Settings -> Build, Execution, Deployment -> Python Debugger

This option has put an incredible handbrake on the debugger :-(. I just had to revert to the original settings.

The Python configuration is specified in (at least) two places: Run | Edit Configurations | Python | Python Interpreter , and File | Settings | Project | Project Interpreter . My mistake was I did not set the correct Python installation in the File | Settings . . Hence, it was referring to a Python configuration that did not have the import installed (e.g. NumPy).

After I set these two locations to point to the same, correct Python installation, I did a File | Invalidate Caches / Restart , then it was fine.

A third place to check is File | Default Settings. | Project Interpreter and make sure it matches the other settings.

PyCharm developer posted a workaround for one possible cause of inspection failure:

Gist of it — inspection may fail if you have a venv folder in the project directory. Right click it, mark directory as excluded.

The following often helps to solve false-positive unresolved references

Thanks, have been trying for a while to fix this and your solution finally told me how. I have no idea why anyone would downvote it.

in my case I’d destroyed and re-cloned a repository in the same directory while I had PyCharm on. I think that may have caused some issue with the Caches. This fix seems like it was the most appropriate (and it worked like a charm). Thank you.

In PyCharm’s Project tool window, right-click on the directory and select Mark Directory As -> Sources Root.

In my case I was importing modules I’d written in the same project, but different directories. You need to mark EVERY directory containing said modules as ‘Sources Root’ in fact.

I run into a similar issue when refreshing my virtual env. I’ve found that the following solves my issue:

  1. Click on the python version in the bottom (right) bar to bring up the interpreter selection menu
  2. Click on the the desired interpreter (might already be selected — but click it anyway)
  3. Clicking it will update the skeletons

enter image description here

You can disable inspections to specific libraries (such as numpy). I found this very helpful since my scrollbar was constantly lit up all over due to this issue. Go to Settings -> Editor -> Inspections -> Python -> Unresolved references (near the bottom) and go to the Ignore references section at the bottom right of the window.

Add an entry with «numpy.*» without the quotes and you won’t see these unresolved references in numpy lighting up your scrollbar any more!

I was able to resolve the issue simply using a virtualenv instead of the system interpreter. None of the other methods i found anywhere worked for me before.

I am using Windows 7, PyCharm Community Edition 2018.2.4, Python 3.6.7, Numpy 1.15.4

  1. Create a new project named my_project and set it to use the system interpreter File -> Settings -> Project: my_project -> Project Interpreter -> Select your project -> Select the system interpreter
  2. Create following test script script1.py inside the project:
import numpy as np print(np.tan(8)) 
$cd dir/to/my_project $virtualenv venv $venv\Scripts\activate (venv) $pip install numpy (venv) $deactivate 

This way I was able to fix the same problem for other packages like torch and opencv (simply creating a virtual environment with all the packages I need). No more unresolved references so far.

No idea why it would work this way but would not work with the system interpreter.

Источник

Решение проблемы «Unresolved reference» в PyCharm

A programmer struggling with

При работе с Python и его средой разработки PyCharm, новички часто сталкиваются с проблемой «Unresolved reference». Это сообщение об ошибке говорит о том, что PyCharm не может найти определенный модуль или ссылку на него. Рассмотрим типичный пример.

Представим, что у нас есть следующая структура каталогов:

. ├── main.py ├── helpers │ ├── helper.py 

В main.py мы пытаемся импортировать функции из helper.py следующим образом:

from helpers.helper import some_function

Но PyCharm выдает ошибку «Unresolved reference» и не может найти модуль helpers.helper .

Причина проблемы

В большинстве случаев причина ошибки «Unresolved reference» заключается в том, что PyCharm не может определить путь к модулю, который вы пытаетесь импортировать. Это может произойти, если модуль находится в другом каталоге, и PyCharm не знает, где искать этот каталог.

Решение проблемы

Чтобы решить эту проблему, необходимо сделать так, чтобы PyCharm знал, где искать модули для импорта. Для этого нужно добавить нужный каталог в системный путь Python.

В Python пути к модулям хранятся в переменной sys.path . Это список строк, каждая из которых представляет собой путь к каталогу. Когда Python пытается импортировать модуль, он ищет его в этих каталогах.

Чтобы добавить каталог в sys.path , можно использовать функцию sys.path.append() . Например, если мы хотим добавить каталог helpers в sys.path , мы можем сделать это следующим образом:

import sys sys.path.append("/path/to/helpers") from helpers.helper import some_function

Заключение

В этой статье мы рассмотрели, как решить проблему «Unresolved reference» в PyCharm. Эта проблема часто возникает у новичков, и ее решение поможет понять, как работает импорт модулей в Python и как управлять путями к модулям.

Источник

Оцените статью