"with" 可以用作 Python 中的标识符吗?

Can "with" be used as an identifier in Python?

我正在努力调整第三方 Python 包用于 Python 2.7(据称)以与 Python 2.6 一起使用,虽然已经过时,但仍然是我权限范围内的许多机器上的标准 Python。

我一直在使用 compileall 模块来帮助我识别兼容性问题,实际上我发现的很少。其中只有一个被证明非常有抵抗力:提供给我的代码在几个地方使用 "with" 作为标识符,都作为关键字参数

newitems.append(Data(item[:, Numeric.NewAxis], with='lines'))

并作为属性名称

self.with = keyw['with']

。鉴于 "with" 自 Python 2.6.

以来一直是关键字,因此字节编译器对 "with" 的那些用途感到厌烦

由于该模块的最新修订日期明显是在 2010 年初,而且它的血统书可以追溯到更早的时候,我倾向于认为该模块从未在 Python 2.7 中工作过(正如所声称的那样)甚至在 Python 2.6 中也没有。还有其他合理的结论吗?除了在有问题的上下文中用不同的标识符替换 "with" 之外,还有其他明智的方法吗?

不,不能。 with 在 Python 中被列为保留字,也称为关键字。来自 Python 2.7 Docs:

The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers.

Python 2.6 Docs and even the Python 2.5 Docs. This means that the module did not work, and most likely the only solution would be to change the withs to another word. If you are using Vim, this 中的说法可能有助于简化任务。


尝试在您的 Python 代码中使用 with 将导致 SyntaxError: invalid syntax

>>> with = True
  File "<stdin>", line 1
    with = True
         ^
SyntaxError: invalid syntax