mike
mike

Reputation: 1764

Why python allows to overwrite builtin constants?

Although True, False are builtin constants, the following is allowed in Python.

>>> True = False
>>> a = True
>>> b = False
>>> print a,b
False False

Any reference of why this is allowed?

EDIT: This happens only in Python 2.x (as all pointed out).

Upvotes: 1

Views: 664

Answers (3)

mgilson
mgilson

Reputation: 310287

I think that the python ideology of "We're all consenting adults here" applies here as well. Python doesn't have private class members because there's no real good reason to prevent a user from messing with something ... If they go poking around with things they don't understand, then they'll get what they deserve when the code breaks. The same thing goes with the ability to re-assign builtins ...

list = tuple

Note that the case that you asked about is explicitly disallowed in python 3.x, but you can still assign to builtins ...

>>> True = False
  File "<stdin>", line 1
SyntaxError: assignment to keyword
>>> list = tuple

Upvotes: 9

NlightNFotis
NlightNFotis

Reputation: 9803

Keep in mind that this only happens in versions of Python that were before python 3. This was part of Python's philosophy that everything should be dynamic.

In fact in Python 2 True is not a keyword. It is a reference bound to a bool object. You can try it in your python 2.x vm:

>>> type(True)
<type 'bool'>

In python 3 it is changed to a keyword, and trying to rebind the reference results in an exception:

>>> True = []
  File "<stdin>", line 1
SyntaxError: assignment to keyword

Upvotes: 4

Wooble
Wooble

Reputation: 90037

Traditionally Python is designed with as few keywords as are necessary for the syntax; before py3K, True and False weren't considered necessary keywords. Unless Guido comes across this question before it's closed, you'll likely not get a great answer. (But this thread illustrates why it wasn't changed earlier)

Upvotes: 1

Related Questions