[Python-Dev] Boolean transition
Tim Peters
tim.one@comcast.net
2002年3月10日 20:42:24 -0500
>> days_in_year = 365 + is_leap(year)
[Greg Ewing]
> This is bug-prone, because it relies on is_leap 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 <wink>.
> I don't think it would be a bad thing if you had to write it
>> days_in_year = 365 + ord(is_leap(year))
>> or, even better,
>> days_in_year = 365 + bit(is_leap(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
>> days_in_year = 365 + 1 if is_leap(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 <wink>.