Assignment Operators?

Grant Edwards invalid at invalid.invalid
Thu Oct 2 16:23:07 CEST 2014


On 2014-10-02, Chris Angelico <rosuav at gmail.com> wrote:
> On Thu, Oct 2, 2014 at 11:24 PM, Didymus <lynto28 at gmail.com> wrote:
>>>>> errors = False
>>>>> errors |= 3
>>>>> errors
>> 3
>>>>> errors |= 4
>>>>> errors
>> 7

[...]

> When you use False there, it's equivalent to zero.

Why is that, you ask?  [Or should, anyway]

The fact that booleans when found in an arithmetic context are
auto-magically coerced into integers with values 0,1 is a rather
unpythonic wart which has it's historical roots in the time when
Python didn't have a boolean type.  People used integers instead and a
lot of code bound the names True and False to the integers 1 and 0.

When the boolean type was introduced it was decided that backwards
compatibility with that practice was important.  This resulted in two
pragmatic but somewhat "impure" decisions:

 1) In Python 2, True and False are not keywords, they're just global
    keywords that come pre-bound to the boolean singleton values of
    'true' and 'false'.  You can re-bind them to other objects:

      Python 2.7.7 (default, Aug 20 2014, 11:41:28)

      >>> False = 3.14159
      >>> if False: print "False"
      ... 
      False
      >>>
      >>> import math
      >>> math.cos(False)
      -0.9999999999964793

 2) When used in an arithmetic context, boolean values would be
    converted into integer values 0,1.

When Python 3 came out, 1) was dropped and True/False were "promoted"
to keywords.  But, 2) is still the case.

-- 
Grant Edwards               grant.b.edwards        Yow! I guess you guys got
                                  at               BIG MUSCLES from doing too
                              gmail.com            much STUDYING!



More information about the Python-list mailing list