The Python Oracle

True and False in python can be reassigned to False and True respectively?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island

--

Chapters
00:00 Question
01:32 Accepted answer (Score 11)
02:03 Answer 2 (Score 3)
03:12 Thank you

--

Full question
https://stackoverflow.com/questions/4961...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python2x

#avk47



ACCEPTED ANSWER

Score 13


In Python 2, True and False are builtin "constants". You are quite right about it not being safe. But Python doesn't actually have constants, so to make it impossible to assign a different value, they need to be keywords. True and False are keywords in Python 3. But it would have been disruptive to add these new keywords to Python 2.




ANSWER 2

Score 3


BoarGules answer is mostly correct but incomplete. The built-in bool type and built-in False and True were add in one of the 2.2.z releases. (This was before the 'no new features in maintenance releases' rule. Indeed, the confusion engendered by the mid-version addition is one of the reasons for the rule.)

Before this addition, people who wanted to use False and True had to write something like the following near the top of their code.

False, True = 0, 1

Making False and True uneditable keywords would have broken existing code. That would indeed have been distruptive. After the addition, people could optionally edit their code to

try:
    False
except NameError:
    False, True = 0, 1

in order, when running with newer 2.x releases, to have False and True be bools, and print as 'False' and 'True' instead ints printing as 0 and 1.

In 3.0, when most people had dropped support for 2.2 and before, and hence no longer needed the assignment alternative, False and True were made keywords.