Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Solution 2:

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 boolobject. 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 1SyntaxError: assignment to keyword

Post a Comment for "Why Python Allows To Overwrite Builtin Constants?"