d-coder
d-coder

Reputation: 13993

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

I think I just witnessed something really scary and hard to digest!

So in my projects I came across this beautiful piece of code

from CoreDefaults import FALSE, TRUE

After looking into the CoreDefaults module I saw this

TRUE = 1 == 1     # some part of my mind was blown here
FALSE = 0 == 1    # which I honestly thought was clever and it really is!

But then it raised a question that when python gives default True and False why would anyone evaluate the value of True and False and then assign to such variables but then I got a hunch that the only reason anyone would do was if those values can be reassigned!

So I tried the following

>>> True
True
>>> False
False
>>> True = False   # True is assigned to False and it is NOT OK ?
>>> True
False              # Python, I think it's over between you and me. 

Is this behavior normal ? Is this the way it's supposed to be implemented ? Why not make it non-editable ? Is this a security risk when using python or is it the same with other languages too ? Any clever way of making it more non-editable like any builtin I need to override ? How do I fall asleep tonight ?

I'm using python 2.6.6.

EDIT 1 : So can we use 0 and 1 instead of False and True instead ? I think it's more fail proof though ?

Upvotes: 9

Views: 4070

Answers (2)

Terry Jan Reedy
Terry Jan Reedy

Reputation: 19219

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.

Upvotes: 3

BoarGules
BoarGules

Reputation: 16951

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.

Upvotes: 13

Related Questions