问题描述
我刚刚发现了一个错误,如果 list
是 Python 中的保留字,该错误本可以避免.(可以肯定的是,我是 Dumbery.)
I just got bit by a bug that would have been prevented if list
were a reserved word in Python. (Dumbery on my part, to be sure.)
那么为什么 list(或 dict 或 float 或任何类型)不是保留字?添加解释器错误似乎比尝试记住规则更容易.
So why isn't list (or dict or float or any of the types) a reserved word? It seems easier to add an interpreter error than to try and remember a rule.
(我也知道 Eclipse/PyDev 有一个设置会提醒你这个规则,这很有用.)
(I also know Eclipse/PyDev has a setting that will remind you of this rule, which can be useful.)
推荐答案
Only keywords 保留.
list
不是关键字而是内置类型,str
、set
、dict
也是、unicode
、int
、float
等
list
is not a keyword but a built-in type, as are str
, set
, dict
, unicode
, int
, float
, etc.
保留每一种可能的内置类型是没有意义的;python 是一种动态语言,如果你想用一个隐藏它的本地名称替换内置类型,你应该可以.
There is no point in reserving each and every possible built-in type; python is a dynamic language and if you want to replace the built-in types with a local name that shadows it, you should be able to.
将 list
和其他类型视为预先导入的对象类型库;您不希望 collections
中的 defaultdict
也被保留吗?
Think of list
and the other types as a pre-imported library of object types; you wouldn't expect defaultdict
from collections
to be reserved either?
使用静态代码分析器 捕捉这样的错误;大多数 IDE 可让您轻松集成其中一个.
Use a static code analyzer to catch errors like these; most IDEs let you integrate one with ease.
这篇关于为什么“列表"不是 Python 中的保留字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!