Putting a pleasant Python surprise to use
Although I've been programming in Python for a few years now, it keeps surprising me with little bits and pieces. Here's a neat Python language feature that I recently used for the first time (discovered originally through Bram Cohen's LiveJournal).
A common programming pattern is 'search for a something to work on, but stop if you don't find anything'. In Python one might write it something like this (taken more or less from DWiki's source):
found = False for dir in utils.walk_to_root(curdir): page = dir.child("__readme") if page.exists(): found = True break if not found: return '' # Go on to use the __readme file we found in some directory.
Python allows you to put 'else' conditions on loops (both for
and
while
loops); the else condition is executed if the loop completed
instead of being break
'd from. This lets us simplify this pattern down
to:
for dir in utils.walk_to_root(curdir): page = dir.child("__readme") if page.exists(): break else: return ''
If there's no __readme
file to be found from the current directory
up to the root, we just return nothing; otherwise, we'll process it.
This DWiki code is the first occasion I've had to use this feature since
I discovered it, and I'm pleased to finally have been able to.
(As you can now see, not all the entries in this blog are going to be long and meandering.)
|
|