A Python (non-)idiom that I should really avoid

December 17, 2010

One of my bad habits as a Python programmer is that I am both lazy and impatient. I will go out of my way to do something overly clever just because it saves me some boring boiler-plate code, and because Python is such a compact language already my threshold for this irritation is very low.

One of the things that this leads me to is writing conditional variable initializations like this:

var = None
if condition:
    var = something()

I've recently come to the conclusion that this is a bad idiom that I should avoid. On the 'good' side, I've saved a line and the annoyance of writing the boiler-plate if/else (at the trivial cost of an extra assignment). On the bad side, what I've found recently is that that the 'var = None' assignment can easily look a little bit too much like it could have been a temporary addition done for debugging or code testing. In fact I almost removed such an initialization today during a cleanup pass of stripping my debugging and testing code from a program before committing the changes to the repository. Actually putting the else: in makes it clear to me that both initializations are supposed to be there.

(Of course there's all the general style and 'clever: -5 points' issues involved with writing code like this. But, well, I'm lazy and impatient and so I sometimes do this stuff anyways.)

I suppose I should be thankful that I don't really like Python's conditional expressions, and also that I'm still writing code for Python 2.4.6, which doesn't have them so I don't have a choice about liking or not liking them. Writing the above as:

var = something() if condition else None

is just far too clever, partly because I find that the order makes it hard to read.


Written on 17 December 2010.
« Sometimes bugs have very small edit distances
A tale of memory allocation failure »

These are my WanderingThoughts
(About the blog)

Full index of entries
Recent comments

This is part of CSpace, and is written by ChrisSiebenmann.
Twitter: @thatcks

* * *

Categories: links, linux, programming, python, snark, solaris, spam, sysadmin, tech, unix, web

This is a DWiki.
GettingAround
(Help)

Search:

Page tools: View Source, Add Comment.
Search:
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Fri Dec 17 23:55:14 2010
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.