【问题标题】:Why can type hints not be used in for loops?为什么不能在 for 循环中使用类型提示?
【发布时间】:2020-03-24 21:20:02
【问题描述】:

for 语句中注释目标无效:

>>> for i: str in test_string:
  File "<stdin>", line 1
    for i: str in test_string:
         ^
SyntaxError: invalid syntax

我想知道此时拒绝注释的原因。

【问题讨论】:

  • 你想做什么?
  • 因为类型检查器应该足够聪明,知道str.__iter__ 返回Iterator[str]
  • for str(i) in test_string:
  • 请澄清您所说的“为什么”是什么意思。你的意思是为什么决定这样实施它?你的意思是为什么这通常具有挑战性?

标签: python python-3.x


【解决方案1】:

冒号 : 在 Python 中历来有多种含义。例如,它表示块的开始 (with a as b:)、切片订阅 (a[:]) 和字典对 ({a: b})。

这使得在某些位置引入: 类型提示变得不可能或至少模棱两可。具体来说,forwith 等块标头与 : 的含义相冲突,表示标头的结束。虽然可以定义明确的语法,但这需要权衡未来维护和扩展语法的需求。到目前为止,这被认为不值得。

PEP 526 - Rejected/Postponed Proposals

withfor 语句中允许注释: 这被拒绝了,因为在for 中它很难发现实际的可迭代对象,而在with 中它会混淆CPython 的 LL(1) 解析器。


暂时可以使用前置类型提示,或者内联类型注释:

a: str
for a in my_iterable:
    ...

for b in my_iterable:  # type: str
    ...

PEP 526 – Where annotations aren't allowed

只允许单个赋值目标和单个右侧值。此外,不能注释在 for 或 with 语句中使用的变量;它们可以提前注释,类似于元组解包: [...]

【讨论】:

    【解决方案2】:

    您需要根据https://www.python.org/dev/peps/pep-0526/#where-annotations-aren-t-allowed在循环之前启动它

    所以你可以这样做

    i : str
    for i in test_string: 
        ......
        ......
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      • 2018-07-25
      • 1970-01-01
      • 1970-01-01
      • 2019-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多