[Python-Dev] Boolean transition (original) (raw)

Tim Peters tim.one@comcast.net
Sun, 10 Mar 2002 20:42:24 -0500


daysinyear = 365 + isleap(year)

[Greg Ewing]

This is bug-prone, because it relies on isleap always returning a "normalised" boolean value.

In more than 20 years of writing code exactly like that, I guess it's a miracle I've never had a bug due to it .

I don't think it would be a bad thing if you had to write it

daysinyear = 365 + ord(isleap(year)) or, even better, daysinyear = 365 + bit(isleap(year)) where bit() is a function that takes a boolean (and only a boolean) and returns 0 or 1.

Bleech. It's much more sensible to ensure that the is_leap() implementation on its own fulfills its contract. Then you can simply trust it. Whichever function is computing days_in_year may well want to assert that the result it computes 365 or 366, but it's got no business questioning the functions it relies on.

... and similarly

daysinyear = 365 + 1 if isleap(year) else 0 (Yes, I know that one's already been rejected. I can't stop liking it, though...)

Heh. I immediately read that as

days_in_year = (365 + 1) if is_leap(year) else 0

I'm old enough to wish reality played along .