Friday, December 3, 2010

Python Code Style

Code conventions are important in software development. In Python, where whitespace (specifically indentation) can have a functional impact on your software, coding conventions are critical, especially when code needs to be shared and reused.

Python does have a widely accepted (and widely tweaked) Style Guide called PEP 8. I saw it a while ago but didn't have the time to digest and then laboriously apply it to my active codebases.

When I recently rebooted my development environment on Ubuntu and Mac OSX I noticed the PyDev IDE (now shipping with Aptana Studio)  had support for PyLint. PyLint - like other 'linting' programs - can examine your code and find non-compliances to a specific standard of code formatting. PyLint, when used as commandline tool, can provide a detailed report on your code style.

The great thing about the integration with PyDev, however, is that PyLint shows non-compliances in your currently open files and flags them as warnings and problems in your problems view. This makes deciding to implement and meet a code standard a lot less cognitively burdensome.

PyLint also highlights bad code smells - components and practices which don't smell right that might need refactoring. PyLint can be given global instructions to ignore certain issues, or specific source files can include comments to change how PyLint analyses the file. This gives some ability to customise the behaviour and ignore PyLint where pragmatic.

To enable PyLint in PyDev, first make sure PyLint is installed. Installing PyLint is as easy as installing any python program:

$sudo easy_install pylint

If you have different python versions in your environment, use the correct invocation of SetupTools for that version. I need to target Python2.5 for Google App Engine, so I use:

$sudo easy_install-2.5 pylint

Once pyLint is installed, within Eclipse (or Aptana etcetera) visit the Preferences page and specifically the PyDev > PyLint section in the hierarchy. Locate the actual PyLint script (lint.py) and enable PyLint.

PyLint is really helping me clean up my code (I admit it - I am a recovering tab-fiend).

No comments:

Post a Comment