[Python-ideas] Programming recommendations (PEP 8) and boolean values
steve at pearwood.info
Wed Aug 8 19:44:12 CEST 2012
On 09/08/12 03:27, Bruce Leban wrote:
> On Wed, Aug 8, 2012 at 9:59 AM, Oleg Broytman<phd at phdru.name> wrote:
>> On Thu, Aug 09, 2012 at 02:18:53AM +1000, Ben Finney<
>> ben+python at benfinney.id.au> wrote:
>>> What is a compelling use case for checking precisely for True or False?
>> To distinguish False and None for a tri-state variable that can have
>> 3 values - "yes", "no" and "unspecified" - True, False and None in
> I'd probably write that this way:
> if t is None:
> # not specified
> elif t:
> # true
> # false
Which treats None specially, otherwise falls back to the standard Python
concept of truth-value or truthiness. Which is just a form of duck-typing.
> on the other hand, if I had a variable that could be either a number or
> True/False, I would probably write:
This sounds like poor design to me, but okay, for the sake of the
argument, let's accept that you do.
> if t is True:
> elif t is False:
> # use t as a number
> just as I would for any other singleton value.
Keeping the duck-typing of truth-values:
if isinstance(t, numbers.Number) and not isinstance(t, bool):
elif t: # True, or any other true-like value
else: # False, or any other false-like value
There are many subtle variations on this. We surely don't need, or want,
to have to cover them in PEP 8.
> Why does the PEP say that == True is preferred to is True?
Because there surely are still libraries out there that return 0 and 1
as true/false values. The bool type was introduced in (by memory)
Python 2.2 or 2.3, so very old code may fail, or worse, silently do the
wrong thing if you use "is True".
More information about the Python-ideas