Why python allows to overwrite builtin constants?

南楼画角 提交于 2019-12-13 18:46:43

问题


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).


回答1:


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



回答2:


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



回答3:


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)



来源:https://stackoverflow.com/questions/14979488/why-python-allows-to-overwrite-builtin-constants

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!