Using Pylint with Django
I would very much like to integrate pylint into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:E1101: *%s %r has no %r
member*
--constantly reports errors when using common django fields,
for example:
E1101:125:get_user_tags: Class 'Tag' has no 'objects' member
which is caused by this code:
def get_user_tags(username):
"""
Gets all the tags that username has used.
Returns a query set.
"""
return Tag.objects.filter( ## This line triggers the error.
tagownership__users__username__exact=username).distinct()
# Here is the Tag class, models.Model is provided by Django:
class Tag(models.Model):
"""
Model for user-defined strings that help categorize Events on
on a per-user basis.
"""
name = models.CharField(max_length=500, null=False, unique=True)
def __unicode__(self):
return self.name
How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of objects
, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.)
Edit: The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :)
See here for a summary of the problems I've had with pychecker
and pyflakes
-- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)
Asked by: Roman435 | Posted: 28-01-2022
Answer 1
Do not disable or weaken Pylint functionality by adding ignores
or generated-members
.
Use an actively developed Pylint plugin that understands Django.
This Pylint plugin for Django works quite well:
pip install pylint-django
and when running pylint add the following flag to the command:
--load-plugins pylint_django
Detailed blog post here.
Answered by: Cherry732 | Posted: 01-03-2022Answer 2
I use the following: pylint --generated-members=objects
Answer 3
If you use Visual Studio Code do this:
pip install pylint-django
And add to VSC config:
"python.linting.pylintArgs": [
"--load-plugins=pylint_django"
],
Answered by: John527 | Posted: 01-03-2022
Answer 4
My ~/.pylintrc contains
[TYPECHECK]
generated-members=REQUEST,acl_users,aq_parent,objects,_meta,id
the last two are specifically for Django.
Note that there is a bug in PyLint 0.21.1 which needs patching to make this work.
Edit: After messing around with this a little more, I decided to hack PyLint just a tiny bit to allow me to expand the above into:
[TYPECHECK]
generated-members=REQUEST,acl_users,aq_parent,objects,_meta,id,[a-zA-Z]+_set
I simply added:
import re
for pattern in self.config.generated_members:
if re.match(pattern, node.attrname):
return
after the fix mentioned in the bug report (i.e., at line 129).
Happy days!
Answered by: Andrew113 | Posted: 01-03-2022Answer 5
django-lint is a nice tool which wraps pylint with django specific settings : http://chris-lamb.co.uk/projects/django-lint/
github project: https://github.com/lamby/django-lint
Answered by: Julia728 | Posted: 01-03-2022Answer 6
Because of how pylint works (it examines the source itself, without letting Python actually execute it) it's very hard for pylint to figure out how metaclasses and complex baseclasses actually affect a class and its instances. The 'pychecker' tool is a bit better in this regard, because it does actually let Python execute the code; it imports the modules and examines the resulting objects. However, that approach has other problems, because it does actually let Python execute the code :-)
You could extend pylint to teach it about the magic Django uses, or to make it understand metaclasses or complex baseclasses better, or to just ignore such cases after detecting one or more features it doesn't quite understand. I don't think it would be particularly easy. You can also just tell pylint to not warn about these things, through special comments in the source, command-line options or a .pylintrc file.
Answered by: Justin980 | Posted: 01-03-2022Answer 7
I resigned from using pylint/pychecker in favor of using pyflakes with Django code - it just tries to import module and reports any problem it finds, like unused imports or uninitialized local names.
Answered by: Elise609 | Posted: 01-03-2022Answer 8
This is not a solution, but you can add objects = models.Manager()
to your Django models without changing any behavior.
I myself only use pyflakes, primarily due to some dumb defaults in pylint and laziness on my part (not wanting to look up how to change the defaults).
Answered by: Owen978 | Posted: 01-03-2022Answer 9
Try running pylint with
pylint --ignored-classes=Tags
If that works, add all the other Django classes - possibly using a script, in say, python :P
The documentation for --ignore-classes
is:
--ignored-classes=<members names>
List of classes names for which member attributes should not be checked (useful for classes with attributes dynamicaly set). [current: %default]
I should add this is not a particular elegant solution in my view, but it should work.
Answered by: Stuart258 | Posted: 01-03-2022Answer 10
The solution proposed in this other question it to simply add get_attr to your Tag class. Ugly, but works.
Answered by: Dainton532 | Posted: 01-03-2022Answer 11
For neovim & vim8
use w0rp's ale
plugin. If you have installed everything correctly including w0rp's ale
, pylint
& pylint-django
. In your vimrc
add the following line & have fun developing web apps using django.
Thanks.
let g:ale_python_pylint_options = '--load-plugins pylint_django'
Answered by: Sawyer762 | Posted: 01-03-2022
Answer 12
So far I have found no real solution to that but work around:
- In our company we require a pylint score > 8. This allows coding practices pylint doesn't understand while ensuring that the code isn't too "unusual". So far we havn't seen any instance where E1101 kept us from reaching a score of 8 or higher.
- Our 'make check' targets filter out "for has no 'objects' member" messages to remove most of the distraction caused by pylint not understanding Django.
Answer 13
For heroku users, you can also use Tal Weiss's answer to this question using the following syntax to run pylint with the pylint-django plugin (replace timekeeping
with your app/package):
# run on the entire timekeeping app/package
heroku local:run pylint --load-plugins pylint_django timekeeping
# run on the module timekeeping/report.py
heroku local:run pylint --load-plugins pylint_django timekeeping/report.py
# With temporary command line disables
heroku local:run pylint --disable=invalid-name,missing-function-docstring --load-plugins pylint_django timekeeping/report.py
Note: I was unable to run without specifying project/package directories.
If you have issues with E5110: Django was not configured.
, you can also invoke as follows to try to work around that (again, change timekeeping
to your app/package):
heroku local:run python manage.py shell -c 'from pylint import lint; lint.Run(args=["--load-plugins", "pylint_django", "timekeeping"])'
# With temporary command line disables, specific module
heroku local:run python manage.py shell -c 'from pylint import lint; lint.Run(args=["--load-plugins", "pylint_django", "--disable=invalid-name,missing-function-docstring", "timekeeping/report.py"])'
Answered by: Rebecca594 | Posted: 01-03-2022
Similar questions
python - pylint PyQt4 error
I write a program :
from PyQt4.QtCore import *
from PyQt4.QtGui import *
def main():
app = QApplication([])
button = QPushButton("hello?")
button.show()
app.exec_()
if __name__=="__main__":
main()
the file name is t.py,
when I run:
pylint t.py
in ubuntu9.10, pyqt4,
I got this:
pylint t.py
No config file found, using d...
python - Pylint giving errors, but the code works fine
No config file found, using default configuration
************* Module sendmail
C:153,0: Line too long (146/80)
C:156,0: Line too long (105/80)
C:190,0: Line too long (88/80)
F: 8,0: Unable to import 'email.MIMEMultipart'
E: 8,0: No name 'MIMEMultipart' in module 'email'
F: 9,0: Unable to import 'email.MIMEBase'
E: 9,0: No name 'MIMEBase' in module 'email'
E: 10,0: No name 'Encoders' in module 'email'
R: 47,0:s...
python - pylint can't find QtCore in PyQt4
I recently installed Python(x,y) for spyder and the PyQt4 support. I selected pylint during the install process, and loaded up a script from the code resources for 'Rapid GUI Development with Python & Qt4'... specifically the first simple 'alert.pyw' from chapter 4.
Pylint is saying that this is an error:
from PyQt4.QtCore import (QTime, QTimer, Qt, SIGNAL)
...and here is th...
python - How To Run Pylint From Ant
I need to run this command from ant:
pylint -f parseable src/apps/api | tee pylint.out
It outputs a pylint.out file.
I tried this:
<target name="pylint" description="Pylint">
<exec executable="pylint">
<arg line="-f parseable src/apps/api | tee ${basedir}/pylint.out"/>
</exec>
</target>
But that doesn't...
python - Nose tools and pylint
What is the right way to use nose.tools and keep pylint happy?
The following code:
'''
This is a test
'''
import nose.tools
import nose.tools.trivial
nose.tools.assert_equal(1, 1)
nose.tools.assert_equals(1, 1)
nose.tools.trivial.assert_equal(1, 1)
nose.tools.trivial.assert_equals(1, 1)
Results in the following pylint errors:
$ pylint -i y -r n /tmp/aseq.py
*****...
python - How do I get PyDev to show pylint errors in the editor?
I have the latest PyDev (2.8.2) and pylint (1.0.0) installed. I am trying to get pylint errors and warnings to show up in the PyDev editor. It seems to do nothing when I enable it. When I set it to redirect output to the console, it seems to be working correctly (see screenshot).
How can I get it working?
python - How do I hide Pylint 1.2.1 error output when using Django?
I am attempting to integrate pylint into our local project that uses Django (1.6.1), and I had it working with Pylint 0.27.0, but now that I've updated to the latest 1.2.1 some new errors are popping up and I can't seem to get them to go away.
Here's the nature of the error:
from django.db import models
class UserData(models.Model):
# data...
fieldA = models.IntegerField(default=0)
...
python - Pylint code rating fail under
I am building a tox file includes testing, coverage and running pylint. As you may know, pylint generates reports at the end of it includes code rating.
I want pylint not to break my tox build when the rating is over a score same as --cov-fail-under argument of pytest-cov package. By the way, there are two seperate pylint tasks which are for errors and general code rating. Of...
python - What does R0902 of Pylint mean? Why do we have this limit?
What is behind the R0902 limit? Will too many instance attributes slow down the python interpreter or is it simply because too many instance attributes will make the class harder to understand?
python - Pylint does not work in visual studio code
I use Visual Studio code as python IDE on Mac, and everything works fine for me. But a couple of weeks ago I've started to use Windows. And suddenly I'm unable to use pylint in the project I've started on Mac.
I have
explicitly activated pylintEnabled option (=True)
full path to pylint.exe is set ("c:\Anaconda 3...")
pylintrc file with initial hook adding project to pyth...
python - What's the best Django search app?
How can I use a DLL file from Python?
What is the easiest way to use a DLL file from within Python?
Specifically, how can this be done without writing any additional wrapper C++ code to expose the functionality to Python?
Native Python functionality is strongly preferred over using a third-party library.
python - PubSub lib for c#
Is there a c# library which provides similar functionality to the Python PubSub library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.
python - What is the best way to copy a list?
This question already has answers here:
python - Possible Google Riddle?
My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant.
t-shirt
So, I have a couple of guesses as to what it means, but I was just wondering if there is something more.
My first guess is that eac...
How do you check whether a python method is bound or not?
Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?
ssh - How to scp in Python?
What's the most pythonic way to scp a file in Python? The only route I'm aware of is
os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) )
which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host.
I'm aware of Twisted'...
python - How do I create a new signal in pygtk
I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.
python - What do I need to import to gain access to my models?
I'd like to run a script to populate my database. I'd like to access it through the Django database API.
The only problem is that I don't know what I would need to import to gain access to this.
How can this be achieved?
python - How do I edit and delete data in Django?
I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), EDIT it and save it back to the DB. Secondly how do I DELETE the data that's in the DB? i.e. search, select and then delete!
Please show me an example of the code ...
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python