什么是“软关键字”?

2024-04-24 12:36:23 发布

您现在位置:Python中文网/ 问答频道 /正文

根据^{} module的文档,Python 3.9中添加了两个新成员:

  • issoftkeyword
  • softkwlist

然而,他们的文档并没有透露他们的目的。在What's New一文中甚至没有提到这个更改,通常所有API更改都被记录在案。进一步挖掘source code最终会得到这个pull request,其中提到,“这基本上是一个内部工具”“软关键字仍然没有使用”。那么Python的软关键字的用途是什么呢


Tags: 文档目的apisourcenewrequestcode成员
3条回答

软关键字是上下文敏感的关键字。例如,它允许您使用class作为变量名,只要它不能被解释为定义类。例如,它允许使用cls替换class

今天这是不可能的,因为class是一个关键词:

>>> def a(class):
  File "<stdin>", line 1
    def a(class):
          ^

考虑到上下文,很明显用户并不打算定义一个新类,而是想要一个名为class的标识符

Short:软关键字仍然可以用作变量名或参数名。

PEP 622透露了一些信息(我的重点):

The difference between hard and soft keywords is that hard keywords are always reserved words, even in positions where they make no sense (e.g. x = class + 1), while soft keywords only get a special meaning in context.

[...] The match and case keywords are proposed to be soft keywords, so that they are recognized as keywords at the beginning of a match statement or case block respectively, but are allowed to be used in other places as variable or argument names.

我认为最好用演示来解释这一点asyncawait是Python 3.5和3.6中的软关键字,因此它们可以用作标识符:

>>> async = "spam"
>>> async def foo():
...     pass
...
>>> await = "bar"
>>> async, await
('spam', 'bar')

但在Python 3.7中,它们变成了合适的关键字,只能在有意义的特定上下文中使用:

>>> async = "123"
  File "<stdin>", line 1
    async = "123"
          ^
SyntaxError: invalid syntax
>>> async def foo():
...     pass
...
>>> await = "bar"
  File "<stdin>", line 1
    await = "bar"
          ^
SyntaxError: invalid syntax
>>> async, await
  File "<stdin>", line 1
    async, await
         ^
SyntaxError: invalid syntax

首先将它们作为软关键字引入的想法主要是不破坏任何使用它们作为标识符的现有代码。同样的道理也适用于即将到来的match关键字,例如re.match和数百万个项目

相关问题 更多 >