Object Relational Mappers are evil (a meditation)
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Wed Dec 23 22:02:57 EST 2009
On Wed, 23 Dec 2009 20:11:25 -0500, Terry Reedy wrote:
>>> Instead the accepted, idiomatic Python way of writing this was to use
>>> short-circuit booleans:
>>>
>>> result = condition and x or y
>>>
>>> However this idiom is buggy! If x is a false-value (say, 0) then
>>> result gets set to y no matter what the value of condition.
>
> This is only a bug if one expects otherwise.
I'm not saying the behaviour of `a and x or y` is buggy, but that it's
use as a replacement for a ternary conditional expression is buggy; the
*idiom* is buggy, not the behaviour of and/or.
If I say "you can make perfect hard boiled eggs by putting the egg in a
glass of water in the microwave on high for eight minutes", and the egg
explodes, that's not a bug in the microwave, that's a bug in the recipe.
>>> This buggy idiom survived many years of Python development, missed by
>>> virtually everyone.
>
> The last statement is false. The hazard of using and/or was well-known
> back in '97 or so when I discovered or learned it and I believe it was
> mentioned in the FAQ entry on the subject.
We can argue about how well-known it was for somebody like Raymond
Hettinger to miss it, and for whoever did a code-review of his
application to also miss it.
> The new alternative has the
> hazard that the condition and if-branch must be written and read in a
> backwards order.
If you had asked me a couple of years ago, I would have agreed, but I've
now come to the conclusion that `x if condition else y` is not only
perfectly natural, but at least as natural as the conventional order of
`if condition then x else y` (at least for expressions, not for if
statements).
"Steven, what are you doing on Monday night?"
"Going to the movies if I can get away from work on time, otherwise
sitting at home answering questions on comp.lang.python."
--
Steven
More information about the Python-list
mailing list