15

Possible Duplicate:
Why can’t Python handle true/false values as I expect?

Seems a stupid question, but why is the following statement in Python not explicitly forbidden?

>> True=False
>> True
False

How is True and False handled by Python interpreter?

Community
  • 1
  • 1
linello
  • 8,451
  • 18
  • 63
  • 109

4 Answers4

6

True, just like str or any other builtin, is just a name that exists in the scope by default. You can rebind it like any other such name.

wRAR
  • 25,009
  • 4
  • 84
  • 97
  • 1
    Actually the OP creates `__main__.True`. `__builtin__.True` is still accessible – jfs Nov 15 '12 at 16:18
  • 3
    `None = 42` results in a `SyntaxError`. Why doesn't the same logic apply to that name? – martineau Nov 15 '12 at 17:31
  • @martineau: it does apply. True/False are keywords in Python 3. btw, you can assign to None in Python 2.3 – jfs Nov 16 '12 at 05:18
  • @J.F.Sebastian: I don't think you answered my question (which was directed @wRAR anyway). If `None` is just another name, why can't I assign some other value to it as is possible with the names `True` and `str`? – martineau Nov 16 '12 at 07:14
  • @martineau: [`None`, `True`, `False` are keywords](http://docs.python.org/3/reference/lexical_analysis.html#keywords) in Python 3 so you can't rebind them any more. But historically you could: `None` -- before Python 2.4 (`None` was special constant before Python 3.0), `True/False` -- before Python 3.0. `str` is just another name, you can rebind it. – jfs Nov 16 '12 at 11:13
  • @J.F.Sebastian: OK, so what I think you're saying is that in Python 2.7 `None` is a "special constant" which apparently is effectively the same being a keyword with respect to assigning a new value to it. – martineau Nov 16 '12 at 11:28
2

Python actually has very few reserved words. All the rest are subject to redefinition. It's up to you to be careful!

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • 3
    Question was about 2.7, but just sayin' that in 3.x `True` and `False` are included as reserved words and CANNOT be defined. –  Nov 15 '12 at 16:14
2
>>> True = False
False

In the above assignment, True is just a variable like any other variable you use. Its scope is limited to the current scope. So you can assign any values to it like in the below example. Note that the comparison 2 < 3 still prints True, because you have still access to builtin.

>>> True = 3
>>> True
3
>>> 2 < 3
True
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

Typing

True = False

you create a new variable called True, which value you assign to False.

Answering your second question, True and False are customized versions of integers 1 and 0 (technically speaking, subclasses), which just have a different string representation.

kaspersky
  • 3,959
  • 4
  • 33
  • 50