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
(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:
is just far too clever, partly because I find that the order makes it hard to read.
Written on 17 December 2010.
* * *