gpt4 book ai didi

python - 为什么不能在 for 循环中使用类型提示?

转载 作者:行者123 更新时间:2023-12-05 08:25:59 33 4
gpt4 key购买 nike

for 语句中注释目标是无效的:

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

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

最佳答案

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

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

PEP 526 - Rejected/Postponed Proposals

Allow annotations in with and for statement: This was rejected because in for it would make it hard to spot the actual iterable, and in with it would confuse the CPython's LL(1) parser.


目前,您可以使用前置类型提示,或内联类型注释:

a: str
for a in my_iterable:
...

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

PEP 526 – Where annotations aren't allowed

Only single assignment targets and single right hand side values are allowed. In addition, one cannot annotate variables used in a for or with statement; they can be annotated ahead of time, in a similar manner to tuple unpacking:[...]

关于python - 为什么不能在 for 循环中使用类型提示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59102038/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com