Monday, June 21, 2010

Python static code analysis with pylint

Pylint is a python tool that checks if a module satisfies a coding standard. You can install pylint with easy_install (pylint has dependencies on logilab_common and logilab_astng, so consider download them as well in case of offline install).
easy_install pylint
Running checks is pretty easy:
user1@deby:~/devenv/trunk/src$ ../../bin/pylint greatings
No config file found, using default configuration
************* Module greatings
C:  1: Missing docstring
************* Module greatings.helloworld
C:  1: Missing docstring
C: 10:main: Missing docstring
************* Module greatings.tests
C:  1: Missing docstring
W:  4: Relative import 'test_helloworld', should be 
'greatings.tests.test_helloworld'
W:  7:suite: Redefining name 'suite' from outer scope (line 6)
C:  6:suite: Missing docstring
************* Module greatings.tests.test_helloworld
C:  1: Missing docstring
C:  4:HelloworldTestCase: Missing docstring
C:  6:HelloworldTestCase.test_say: Missing docstring
R:  6:HelloworldTestCase.test_say: Method could be a function
W: 12:suite: Redefining name 'suite' from outer scope (line 10)
C: 10:suite: Missing docstring
  ...
Global evaluation
-----------------
Your code has been rated at 5.94/10
The tool also produces a report that include:
  • Statistics by type
  • External dependencies
  • Duplication
  • Raw metrics
  • Messages by category
  • % errors / warnings by module
  • Messages
If you want to change the default behaviour, you can define options in pylintrc file (use --rcfile option to specify a location). Here is an example.
user1@deby:~/devenv/trunk$ wget -P tools/ http://www.\
logilab.org/cgi-bin/hgwebdir.cgi/pylint/raw-file\
/df8f34aa3dd2/examples/pylintrc
user1@deby:~/devenv/trunk$ cd src/
user1@deby:~/devenv/trunk/src$ ../../bin/pylint \
--rcfile=../tools/pylintrc greatings
Read more about pylint here.

2 comments :

  1. I am using ldap in my module .While using pylint I am getting the error like ldap has no member 'OPT_REFERRALS' etc.
    Can anyone help me to fix this.

    Thanks
    Sanjay

    ReplyDelete
  2. I am using ldap in my module .While using pylint I am getting the error like ldap has no member 'OPT_REFERRALS' etc.
    Can anyone help me to fix this.

    Thanks
    Sanjay

    ReplyDelete