Archive for October, 2011

Find For-Else Statements in Python Code

Monday, October 24th, 2011

I came across Ned Batchelder’s post on the for/else construct, which explains its purpose in a different way from the standard Python docs. I’m fairly certain that more than once in my Python career I have been confused, or as one of the commenters put it: “Whenever I see it, I usually require an extra mental cycle to remember what it does”.

It got me paranoid and I wanted to quickly scan through my code to make sure that I haven’t got a lurking bug somewhere. This is the script that I came up with, which takes a .py file and look in its AST to identify such constructs and report them:

This is the first time I’m using the ast module, and it took a grand total of 30 minutes to find the module, read the documentation, experiment on the shell and come up with the script. I’d say that’s a pretty good testament to the power and intuitiveness of Python!

Hope you find it useful!