Wednesday, September 26, 2007

Clean your code: Pylint

pylint is a tool that "analyzes Python source code looking for bugs and signs of poor quality". Now, that can mean optimizing and cleaning your code at a fairly advanced level at which, if you are a beginning programmer like me, you will not get much out of.

However, it can help with lots of small checking too, and improve the form of your Python code in a quick and convenient manner. It will show you problems you might not even know were problems! I have not gotten into too many of the features myself, but some quick examples should show you its utility. Getting it is pretty simple. On Ubuntu for example, installing is only a matter of sudo apt-get install pylint. To run it, just do pylint

It can take a little while to run, and then it spits out several blocks of results. Some examples:
  • C: 68: Line too long (154/80)
    • One of the lines in the file has way too many characters. It is recommended to keep each line at 79 characters or less. To learn why, check out PEP 8, under "Code Lay-out", "Maximum Line Length".
  • C: 5: Operator not preceded by a space
  • W: 40:Frame.__init__: Unused variable 'statusbar'
    • No need for this variable anymore, just taking up space.
  • C: 93:App.OnInit: Invalid name "OnInit" (should match [a-z_][a-z0-9_]{2,30}$)
As can be seen from these examples, the alerts are pretty easy to read. pylint also shows you how many lines are duplicated, metrics such as how many lines of code versus docstrings, how many modules, and more. In the end, it gives your code an overall score. If you fix some errors and re-run it, it will show you your current and previous scores.

To start using the more advanced features, peruse the man page. Now, go clean your code.


Post a Comment

Subscribe to Post Comments [Atom]

<< Home