Find For-Else Statements in Python Code

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!




No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.


This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

Leave a Reply

Please login with your OpenID to post a comment: