Python 中的关键字究竟是什么?

What really is a keyword in Python?

我们可以得到Python个关键字的列表如下:

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

很酷,但我没想到会在那里看到 FalseNoneTrue。它们是内置对象。

为什么 TrueFalseNone 是关键字,而 int 不是?是什么真正使某些东西成为 Python 中的关键字?

编辑:我说的是 Python 3

关键字是保留名称,因此您不能分配给它们。

>>> True = 0
  File "<stdin>", line 1
SyntaxError: can't assign to keyword

int是一种类型;完全可以重新分配它:

>>> int = str
>>>

(不过我真的不推荐这个。)

Python 不像 Javascript。在 Javascript 中,您可以执行 undefined = "defined" 之类的操作(更新:已修复)。

关键字取决于您使用的python。例如:async3.7 中的新关键字。

不过事情并不总是这样,在 Python 2 True = False 中是有效的...

>>> True = False
>>> True
False
>>> True is False
True

所以"They are builtin objects.",是的,但是python的新版本防止你犯傻。这是唯一的原因...

新关键字(自 Python 2.7 起)是:

False
None
True
async
await
nonlocal

当然 execprint 不再是关键字。

在 python 2.6 中你可以做类似 True = False 的事情(真的很混乱)

这可能对你有帮助link

实际上,关键字是 Python 中预定义的保留名称,对语言的解析器具有 特殊含义。有时他们宣布我们即将定义:

  1. 一个类型的实例(就像 defclass 关键字所做的那样)
  2. 条件语句(如ifwhile ...)
  3. ...
  4. 有时它们是实际对象,例如 TrueFalseNone

因为我没有看到提到正文,所以我们有两种类型的关键字:(示例来自python 3.10

1- 硬关键字:(keyword.kwlist)

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break',
 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally',
 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

2- 软关键字:(keyword.softkwlist)

['_', 'case', 'match']

您不能使用硬关键字作为变量名或给它们赋值。它们在所有地方都是保留名称。但是您可以有一个名为 match 的变量,也可以将它们作为普通变量放在表达式中。 match 只有在 match-case 块的第一行才有特殊意义。

来自 PEP 634:

Remember that match and case are soft keywords, i.e. they are not reserved words in other grammatical contexts (including at the start of a line if there is no colon where expected).