I have a pre-commit set up on a python repo. I have a .pre-commit-config.yaml file where I specify my pylint settings/arguments. Previously my pylint hook worked.
Pylint config in .pre-commit-config.yaml:
- repo: local
hooks:
- id: pylint
name: pylint
entry: pylint
language: system
types: [python]
args:
[
"-rn",
"--rcfile=./polestar.rc",
"--fail-under=6"
]
This config previously worked. Now I get the following error.
pylint: error: no such option: --fail-under
I can't think of anything that has changed to cause this issue.
Any advice would be great or suggestions as to what could fix it.
Found issue: the python environment I was in had a old version of pylint installed. I updated the pylint version to latest and the option to set --fail-under became available again.
I am trying to create a basic Development Container to use with VS Code.
I've been through a few iterations no of versions but keep coming up against the same issue, my VS Code extensions cannot seem to see what packages are installed in my venv.
Files in my workspace:
.devcontainer/devcontainer.json
{
"name": "Existing Dockerfile",
"context": "..",
"dockerFile": "../Dockerfile"
}
venv/ containing pip installed pandas
Dockerfile:
FROM python:3.9
WORKDIR .
COPY my_file.py .
my_file.py
import sys
import pandas
print(sys.path)
Output of sys.path incase relevant is ['/workspaces/yt', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/workspaces/yt/venv/lib/python3.9/site-packages']
The code executes fine when ran but in VS Code the linting tools raise an error that pandas is not accessed.
Any help would be greatly appreciated.
The most likely reason is that the environment in which the pandas library was installed is not the same as the environment you are currently using.
Solution
Use Ctrl+Shift+P to open the command palette and search for Python:Select Interpreter to select a correct interpreter.
If the error is still not resolved, go ahead and try the following methods:
Add configuration in settings.json to point to the pandas library.
// Just an example, please modify it to your own path
"python.analysis.extraPaths": [
// Path to pandas library
"C:\\WorkSpace\\PyTest0802\\.venv\\Lib\\site-packages"
],
The most simple and rude method -- cancel this type of error (use with caution, this method will cause the prompt message that there is such an error to not be displayed)
Add the following configuration to the settings.json file
"python.analysis.diagnosticSeverityOverrides": {
"reportMissingModuleSource": "none",
},
i'm using vscode for python3 in Ubuntu. Error-squiggle-lines have stopped working for Python(it works for other languages). And I am using Microsoft's Python extension.
vscode v1.41.1
Ubuntu v18.04
this is what i have tried:
I thought maybe it's because i installed anaconda so uninstalled it but didn't fix it.
then I re-installed vs code after deleting its config from .config/code but that didn't work either.
also set python linting to true from command palette
it's not showing error squiggle lines:
here is the Microsoft's python extension's contributions regarding linting(sorry for poor readability):
Whether to lint Python files. true python.linting.flake8Args Arguments passed in. Each argument is a separate item in the array. python.linting.flake8CategorySeverity.E Severity of Flake8 message type 'E'. Error python.linting.flake8CategorySeverity.F Severity of Flake8 message type 'F'. Error python.linting.flake8CategorySeverity.W Severity of Flake8 message type 'W'. Warning python.linting.flake8Enabled Whether to lint Python files using flake8 false python.linting.flake8Path Path to flake8, you can use a custom version of flake8 by modifying this setting to include the full path. flake8 python.linting.ignorePatterns Patterns used to exclude files or folders from being linted. .vscode/*.py,**/site-packages/**/*.py python.linting.lintOnSave Whether to lint Python files when saved. true python.linting.maxNumberOfProblems Controls the maximum number of problems produced by the server. 100 python.linting.banditArgs Arguments passed in. Each argument is a separate item in the array. python.linting.banditEnabled Whether to lint Python files using bandit. false python.linting.banditPath Path to bandit, you can use a custom version of bandit by modifying this setting to include the full path. bandit python.linting.mypyArgs Arguments passed in. Each argument is a separate item in the array. --ignore-missing-imports,--follow-imports=silent,--show-column-numbers python.linting.mypyCategorySeverity.error Severity of Mypy message type 'Error'. Error python.linting.mypyCategorySeverity.note Severity of Mypy message type 'Note'. Information python.linting.mypyEnabled Whether to lint Python files using mypy. false python.linting.mypyPath Path to mypy, you can use a custom version of mypy by modifying this setting to include the full path. mypy python.linting.pycodestyleArgs Arguments passed in. Each argument is a separate item in the array. python.linting.pycodestyleCategorySeverity.E Severity of pycodestyle message type 'E'. Error python.linting.pycodestyleCategorySeverity.W Severity of pycodestyle message type 'W'. Warning python.linting.pycodestyleEnabled Whether to lint Python files using pycodestyle false python.linting.pycodestylePath Path to pycodestyle, you can use a custom version of pycodestyle by modifying this setting to include the full path. pycodestyle python.linting.prospectorArgs Arguments passed in. Each argument is a separate item in the array. python.linting.prospectorEnabled Whether to lint Python files using prospector. false python.linting.prospectorPath Path to Prospector, you can use a custom version of prospector by modifying this setting to include the full path. prospector python.linting.pydocstyleArgs Arguments passed in. Each argument is a separate item in the array. python.linting.pydocstyleEnabled Whether to lint Python files using pydocstyle false python.linting.pydocstylePath Path to pydocstyle, you can use a custom version of pydocstyle by modifying this setting to include the full path. pydocstyle python.linting.pylamaArgs Arguments passed in. Each argument is a separate item in the array. python.linting.pylamaEnabled Whether to lint Python files using pylama. false python.linting.pylamaPath Path to pylama, you can use a custom version of pylama by modifying this setting to include the full path. pylama python.linting.pylintArgs Arguments passed in. Each argument is a separate item in the array. python.linting.pylintCategorySeverity.convention Severity of Pylint message type 'Convention/C'. Information python.linting.pylintCategorySeverity.error Severity of Pylint message type 'Error/E'. Error python.linting.pylintCategorySeverity.fatal Severity of Pylint message type 'Fatal/F'. Error python.linting.pylintCategorySeverity.refactor Severity of Pylint message type 'Refactor/R'. Hint python.linting.pylintCategorySeverity.warning Severity of Pylint message type 'Warning/W'. Warning python.linting.pylintEnabled Whether to lint Python files using pylint. true python.linting.pylintPath Path to Pylint, you can use a custom version of pylint by modifying this setting to include the full path. pylint python.linting.pylintUseMinimalCheckers Whether to run Pylint with minimal set of rules. true
python.linting.pylintEnabled is: true
python.linting.pylintPath is: pylint
all the errors in visual studio's console of developer tools:
console.ts:137 [Extension Host] Error Python Extension: 2020-01-18 18:35:53: Failed to serialize gatherRules for DATASCIENCE.SETTINGS [TypeError: Cannot convert object to primitive value at Array.join (<anonymous>) at Array.toString (<anonymous>) at /home/manik/.vscode/extensions/ms-python.python-2020.1.58038/out/client/extension.js:1:12901 at Array.forEach (<anonymous>) at Object.l [as sendTelemetryEvent] (/home/manik/.vscode/extensions/ms-python.python-2020.1.58038/out/client/extension.js:1:12818) at C.sendSettingsTelemetry (/home/manik/.vscode/extensions/ms-python.python-2020.1.58038/out/client/extension.js:75:707093) at C.r.value (/home/manik/.vscode/extensions/ms-python.python-2020.1.58038/out/client/extension.js:1:87512) at Timeout._onTimeout (/home/manik/.vscode/extensions/ms-python.python-2020.1.58038/out/client/extension.js:1:86031) at listOnTimeout (internal/timers.js:531:17) at processTimers (internal/timers.js:475:7)]
t.log # console.ts:137
2console.ts:137 [Extension Host] Notification handler 'textDocument/publishDiagnostics' failed with message: Cannot read property 'connected' of undefined
t.log # console.ts:137
2console.ts:137 [Extension Host] (node:21707) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
t.log # console.ts:137
$logExtensionHostMessage # mainThreadConsole.ts:39
_doInvokeHandler # rpcProtocol.ts:398
_invokeHandler # rpcProtocol.ts:383
_receiveRequest # rpcProtocol.ts:299
_receiveOneMessage # rpcProtocol.ts:226
(anonymous) # rpcProtocol.ts:101
fire # event.ts:581
fire # ipc.net.ts:453
_receiveMessage # ipc.net.ts:733
(anonymous) # ipc.net.ts:592
fire # event.ts:581
acceptChunk # ipc.net.ts:239
(anonymous) # ipc.net.ts:200
t # ipc.net.ts:28
emit # events.js:200
addChunk # _stream_readable.js:294
readableAddChunk # _stream_readable.js:275
Readable.push # _stream_readable.js:210
onStreamRead # internal/stream_base_commons.js:166
output for python in output panel:
User belongs to experiment group 'AlwaysDisplayTestExplorer - control'
User belongs to experiment group 'ShowPlayIcon - start'
User belongs to experiment group 'ShowExtensionSurveyPrompt - enabled'
User belongs to experiment group 'DebugAdapterFactory - experiment'
User belongs to experiment group 'AA_testing - experiment'
> conda --version
> pyenv root
> python3.7 -c "import sys;print(sys.executable)"
> python3.6 -c "import sys;print(sys.executable)"
> python3 -c "import sys;print(sys.executable)"
> python2 -c "import sys;print(sys.executable)"
> python -c "import sys;print(sys.executable)"
> /usr/bin/python3.8 -c "import sys;print(sys.executable)"
> conda info --json
> conda env list
Starting Microsoft Python language server.
> conda --version
> /usr/bin/python3.8 ~/.vscode/extensions/ms-python.python-2020.1.58038/pythonFiles/interpreterInfo.py
> /usr/bin/python3.8 ~/.vscode/extensions/ms-python.python-2020.1.58038/pythonFiles/interpreterInfo.py
how to get the squiggle lines to work again?
In your settings.json file(search for settings.json in the command palette), declare the following:
"python.linting.pylintEnabled": true, "python.jediEnabled": false
if you just want the changes in your workspace then change the settings.json file in .vscode folder
In latest version of visual studio code, workspace is not registering settings from checkboxes so you have to explicitly declare in settings.json what settings you want to enable for your workspace. Flake8 is not affected by this. Pylint and Microsoft Python Language Server seem to be not working due to this.
side note:got this solution from sys-temd's reply on github.com/microsoft/vscode-python/issues
What I tried but not working
pip install -U pylint
declare "python.linting.pylintEnabled": true, "python.jediEnabled": false
Then I try to recreate a brand-new settings.json, pylint turns out working.
Therefore, I trace which line affects pylint.
In my case, it's the line beginning from "python.linting.pylintArgs":
Solution
Removing the line beginning from "python.linting.pylintArgs": will solve the problem.
Make sure in your settings you didn't turn off linting (and specifically Pylint if that's what you want to use). Also make sure you have Pylint installed and the Python extension knows where it is (either by creating an environment and installing into there or installing it globally and setting "python.linting.pylintPath"). Otherwise check the output of the "Python" channel in the Output Panel to see how Pylint is being executed and make sure that works when you copy-and-paste it into a terminal as appropriate.
pip install -U pylint
Solved my issue
If the main problem is those squiggle lines or some minor errors in the workspace then you can download the 'pylance extension' and enable it in settings of 'python language server'. This language server is even better (i think) because it is lighter than 'jedi' language server and also tells about the unused modules and variables or even the undefined variables as those squiggle lines show.
Sorry this is a long question. See the sentence in bold at the bottom for the TL;DR version.
I've spent many hours trying to track down a problem where pylint sometimes doesn't report all the errors in a module. Note that it does find some errors (e.g. long lines), just not all of them (e.g. missing docstrings).
I'm running pylint 1.7.2 on Ubuntu 16.04. (The version available from apt was 1.5.2 but installing via pip gives 1.7.2.)
We typically run pylint from tox, with a tox.ini that looks something like this (this is a cut-down version):
[tox]
envlist = py35
[testenv]
setenv =
MODULE_NAME=our_module
ignore_errors = True
deps =
-r../requirements.txt
whitelist_externals = bash
commands =
pip install --editable=file:///{toxinidir}/../our_other_module
pip install -e .
bash -c \'set -o pipefail; pylint --rcfile=../linting/pylint.cfg our_module | tee pylint.log\'
Amongst other things, the ../requirements.txt file contains a line for pylint==1.7.2.
The behaviour is like this:
[wrong] When the line that imports our_other_module is present, pylint appears to complete successfully and not report any warnings, even though there are errors in the our_module code that it should pick up.
[correct] When that line is commented out, pylint generates the expected warnings.
As part of tracking this down I took two copies of the .tox folder with and without the module import, naming them .tox-no-errors-reported and .tox-with-errors-reported respectively.
So now, even without sourcing their respective tox virtualenvs, I can do the following:
$ .tox-no-errors-reported/py35/bin/pylint --rcfile=../linting/pylint.cfg our_module -- reports no linting warnings
$ .tox-with-errors-reported/py35/bin/pylint --rcfile=../linting/pylint.cfg our_module -- reports the expected linting warnings
(where I just changed the pylint script's #! line in each case to reference the python3.5 inside that specific .tox directory instead of the unrenamed .tox)
By diffing .tox-no-errors-reported and .tox-with-errors-reported, I've found that they are very similar. But I can make the "no errors" version start to report errors by removing the path to our_other_module from .tox-no-errors-reported/py35/lib/python3.5/site-packages/easy-install.pth.
So my question is why is pylint using easy_install at runtime, and what is it picking up from our other component that is causing it to fail to report some errors.
As I understand it, pylint has dependencies on astroid and logilab-common, but including these in the requirements.txt doesn't make any difference.
One possible reason for the surprising pylint behavior is the --editable option.
it creates a special .egg-link file in the deployment directory, that links to your project’s source code. And, ..., it will also update the easy-install.pth file to include your project’s source code
The pth file will then affect the sys.path which affects the module import logic of astroid and it is deeply buried in the call stack of pylint.expand_files via pylint.utils.expand_modules. Also pylint identifies the module part and function names in the AST using astroid.modutils.get_module_part.
To test the theory, you can try calling some of the affected astroid functions manually:
import sys, astroid
print(sys.path)
print(astroid.modutils.get_module_part('your_package.sub_package.module'))
astroid.modutils.file_from_modpath(['your_package', 'sub_package', 'module'])
def index(request):
latest_question_list = Question.objects.all().order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {'latest_question_list':latest_question_list}
return HttpResponse(template.render(context, request))
The first line of that function gets an error on Question.objects.all():
E1101: Class 'Question' has no 'objects' member
I'm following the Django documentation tutorial and they have the same code up and running.
I have tried calling an instance.
Question = new Question()
and using MyModel.objects.all()
Also my models.py code for that class is this...
class Question(models.Model):
question_text = models.CharField(max_length = 200)
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
def __str__(self):
return self.question_text
To no avail I still have this error.
I have read about pylint and ran this...
pylint --load-plugins pylint_django
Which didn't help, even tho the github readme file says...
Prevents warnings about Django-generated attributes such as
Model.objects or Views.request.
I ran the command within my virtualenv, and yet nothing.
So any help would be great.
Install pylint-django using pip as follows
pip install pylint-django
Then in Visual Studio Code goto: User Settings (Ctrl + , or File > Preferences > Settings if available ) Put in the following (please note the curly braces which are required for custom user settings in VSC):
{"python.linting.pylintArgs": [
"--load-plugins=pylint_django"
],}
#tieuminh2510's answer is perfect. But in newer versions of VSC you will not find the option to edit or paste that command in User Settings.
For newer versions, add the code in the following steps:
Press ctrl shift p to open the the Command Palette.
Now in Command Palette type Preferences: Configure Language Specific Settings.
Select Python.
Add these lines inside the first curly braces:
"python.linting.pylintArgs": [
"--load-plugins=pylint_django",
]
Make sure that pylint-django is also installed.
Install Django pylint:
pip install pylint-django
ctrl+shift+p > Preferences: Configure Language Specific Settings > Python
The settings.json available for python language should look like the below:
{
"python.linting.pylintArgs": [
"--load-plugins=pylint_django"
],
"[python]": {
}
}
I've tried all possible solutions offered but unluckly my vscode settings won't changed its linter path. So, I tride to explore vscode settings in settings > User Settings > python. Find Linting: Pylint Path and change it to "pylint_django". Don't forget to change the linter to "pylint_django" at settings > User Settings > python configuration from "pyLint" to "pylint_django".
Heres the answer.
Gotten from my reddit post...
https://www.reddit.com/r/django/comments/6nq0bq/class_question_has_no_objects_member/
That's not an error, it's just a warning from VSC. Django adds that
property dynamically to all model classes (it uses a lot of magic
under the hood), so the IDE doesn't know about it by looking at the
class declaration, so it warns you about a possible error (it's not).
objects is in fact a Manager instance that helps with querying the DB.
If you really want to get rid of that warning you could go to all your
models and add objects = models.Manager() Now, VSC will see the
objects declared and will not complain about it again.
UPDATE FOR VS CODE 1.40.0
After doing:
$ pip install pylint-django
Follow this link: https://code.visualstudio.com/docs/python/linting#_default-pylint-rules
Notice that the way to make pylint have into account pylint-django is by specifying:
"python.linting.pylintArgs": ["--load-plugins", "pylint_django"]
in the settings.json of VS Code.
But after that, you will notice a lot of new linting errors. Then, read what it said here:
These arguments are passed whenever the python.linting.pylintUseMinimalCheckers is set to true (the default). If you specify a value in pylintArgs or use a Pylint configuration file (see the next section), then pylintUseMinimalCheckers is implicitly set to false.
What I have done is creating a .pylintrc file as described in the link, and then, configured the following parameters inside the file (leaving the rest of the file untouched):
load-plugins=pylint_django
disable=all
enable=F,E,unreachable,duplicate-key,unnecessary-semicolon,global-variable-not-assigned,unused-variable,binary-op-exception,bad-format-string,anomalous-backslash-in-string,bad-open-mode
Now pylint works as expected.
You can change the linter for Python extension for Visual Studio Code.
In VS open the Command Palette Ctrl+Shift+P and type in one of the following commands:
Python: Select Linter
when you select a linter it will be installed. I tried flake8 and it seems issue resolved for me.
Just adding on to what #Mallory-Erik said:
You can place objects = models.Manager() it in the modals:
class Question(models.Model):
# ...
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
# ...
def __str__(self):
return self.question_text
question_text = models.CharField(max_length = 200)
pub_date = models.DateTimeField('date published')
objects = models.Manager()
Change your linter to - flake8 and problem will go away.
I was able to update the user settings.json
On my mac it was stored in:
~/Library/Application Support/Code/User/settings.json
Within it, I set the following:
{
"python.linting.pycodestyleEnabled": true,
"python.linting.pylintEnabled": true,
"python.linting.pylintPath": "pylint",
"python.linting.pylintArgs": ["--load-plugins", "pylint_django"]
}
That solved the issue for me.
First install pylint-django using following command
$ pip install pylint-django
Then run the second command as follows:
$ pylint test_file.py --load-plugins pylint_django
--load-plugins pylint_django is necessary for correctly review a code of django
If you use python 3
python3 -m pip install pylint-django
If python < 3
python -m pip install pylint-django==0.11.1
NOTE: Version 2.0, requires pylint >= 2.0 which doesn’t support Python 2 anymore! (https://pypi.org/project/pylint-django/)
First, Install pylint-django using pip as follows:
pip install pylint-django
Goto settings.json find and make sure python linting enabled is true
like this:
At the bottom write "python.linting.pylintPath": "pylint_django"like this:
OR,
Go to Settings and search for python linting
make sure Python > Linting: Pylint Enabled is checked
Under that Python > Linting: Pylint Path write pylint_django
How about suppressing errors on each line specific to each error?
Something like this: https://pylint.readthedocs.io/en/latest/user_guide/message-control.html
Error: [pylint] Class 'class_name' has no 'member_name' member
It can be suppressed on that line by:
# pylint: disable=no-member
I installed PyLint but I was having the error Missing module docstringpylint(missing-module-docstring). So I found this answer with this config for pylint :
"python.linting.pylintEnabled": true,
"python.linting.pylintArgs": [
"--disable=C0111", // missing docstring
"--load-plugins=pylint_django,pylint_celery",
],
And now it works
By doing Question = new Question() (I assume the new is a typo) you are overwriting the Question model with an intance of Question. Like Sayse said in the comments: don't use the same name for your variable as the name of the model. So change it to something like my_question = Question().
This issue happend when I use pylint_runner
So what I do is open .pylintrc file and add this
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=objects
Just add objects = None in your Questions table. That solved the error for me.