Operator Precedence/Boolean Logic

Steven D'Aprano steve at pearwood.info
Wed Jun 22 23:59:29 EDT 2016


On Thu, 23 Jun 2016 01:12 pm, Larry Hudson wrote:

> On 06/22/2016 12:42 AM, Lawrence D’Oliveiro wrote:
> [snip]
>> I feel that’s a needlessly complicated rule. It would have been simpler
>> if boolean operators (and conditional expressions like in if-statements
>> and while-statements) only allowed values of boolean types. But that’s
>> one of the few warts in the design of Python...
>>
> 
> Wart??  I *strongly* disagree.  I find it one of the strengths of Python,
> it enhances Python's
> expressiveness.  Of course, everyone is entitled to their own
> opinion...and this is mine.

Allowing any value as a truth value is just applying the principle of
duck-typing to booleans.

There are a pair of canonical truth values, namely True and False, but any
object can quack like a truth value. We often call them:

- true and false (as opposed to True and False);
- true-like and false-like;
- truthy and falsey

values.

Among the builtins, there's a general principle:

- values that represent something should be truthy;
- values that represent nothing should be falsey.

So we have falsey values:

- None
- zeroes (0, 0.0, 0j, etc)
- empty dict {}
- empty sets and frozensets
- empty strings '' and b'' (in Python 2: u'' and '')
- empty lists, tuples and other sequences

and truthy values:

- object
- non-zero numbers
- non-empty dicts
- non-empty sets and frozensets
- non-empty strings
- non-empty sequences

This is an improvement over other languages like Javascript, Ruby, etc where
the division between truthy and falsey appears to be fairly arbitrary.




-- 
Steven




More information about the Python-list mailing list