PyLint plugin to catch if/elif blocks that don't have an 'else' clause
Recently I was tracking down a bug in some code. The source of the problem was an 'if' block that had a elif this, elif that, but it didn't have an 'else' clause. It should have had an else clause. It was going through a loop from a database and checking for certain conditions. It would set a variable based on that if block, since there was no else block, the variable was not getting updated in this iteration of the loop, causing a duplicate of the code. If there had been an 'else: assert False' it wouldn't have been a problem, because we could have caught it. After fixing the code here, I started to wonder about any other potential bugs like this were lurking elsewhere. It would be cool if I could analyse the code and see if there were any more if blocks without an else condition.
pylint is a programme that will scan your python source code for coding standards (variable names, unused imports, line length, etc). It's also extensible, so you can write your own plugin for it. this looked like the perfect tool to use. it turned out to be very straight forward to write a plugin that will scan for this kind of thing.
The code is stored in a git repository here. Anonymouse users can push to the 'mob' branch on this, so I welcome all submissions. It's quite easy to use, just call this command from the same directory as the missing_else.py file from the above repository. It'll generate warning messages for if blocks that have elif blocks but have no else blocks.
There are 2 options with this file. By default it will warn you if you have a if that has an elif and doesn't have an else clause. If you add the option "--warn_if_no_else=y" then it'll also warn you if you have a bare if clause that has no else clause. I don't enable this by default.
You should put a call to PyLint into the precommit hooks in your git/svn/cvs/bzr repo so that it automatically checks all new committed code ;)
Comment by Tom — Mar 31, 2009 10:22:53 AM | # - re
Yeah, we have something similar in work. It checks for calls to start the python debugger. Not exacatly something you need on a production system.
Comment by rory — Mar 31, 2009 7:32:25 PM | # - re
Wow, and I thought I was the only one to find this problem in production code. On a similar note I once found a call to gc.set_debug( ) in module level code.
Comment by Mark Roddy — Apr 1, 2009 2:10:59 AM | # - re
The python debugger, pdb, is a great resource. Since we use svn, it's too easy to check a 'pdb' into svn.
The other thing we're thinking of adding is 'console.log(...)', the firebug javascript logging function. 'console' is undefined on IE and having that in there stops all the JavaScript on IE.
Comment by rory — Apr 1, 2009 10:41:44 AM | # - re
Exactly what I did: fitzgeraldnick.com/weblog/9/
Haven't found anyone else's code examples out there, so hopefully this is helpful to someone...
Comment by Nick Fitzgerald — Dec 6, 2009 1:12:05 AM | # - re