【问题标题】:Should you put quotes around type annotations in python你应该在python中的类型注释周围加上引号吗
【发布时间】:2018-03-09 13:36:45
【问题描述】:

这两个函数有什么区别?我看到人们在类型注释周围加上引号,而其他时候将它们省略,但我找不到人们选择使用其中一个或另一个的原因。

def do_something(entity: Entity):
    pass
def do_something(entity: 'Entity'):
    pass

这些都有优点还是缺点?

【问题讨论】:

  • 我认为 Python 邮件列表上有一些关于使类型注释的解析变得惰性的讨论,以便您可以稍后定义(在您的示例中,在所有代码下方定义 Entity)。跨度>

标签: python python-3.x type-hinting static-typing


【解决方案1】:

根据 PEP 484 在创建 Forward Reference 时,在类型提示周围加上引号是有意义的。在这种情况下,在名称周围加上引号用于抑制可能发生的 NameError。

在其他情况下,不要使用引号,它不会产生你想要的提示:

>>> def bad_foo(a: 'int'):
...     pass
>>> def good_foo(a: int):
...     pass
>>> bad_foo.__annotations__['a'] == good_foo.__annotations__['a']
False

虽然目前类型检查器(mypy,至少)似乎没有区别对待这些,但我不确定将来是否会如此。最好是明确的,当您实际上不需要引号时不要使用它们。

【讨论】:

  • typing.get_type_hints 是使用前向引用解析类型提示的方法,如果您需要这样做的话。
【解决方案2】:

显然,如果您在某些情况下不引用它们,它也会导致运行时异常。见this comment。我不知道为什么,但确实如此:

 ~ python3
Python 3.9.2 (default, Mar 26 2021, 23:27:12)
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def main() -> OrderedDict[str, str]:
...     x: OrderedDict[str, str] = OrderedDict()
...     print(x)
...     return x
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'OrderedDict' is not defined
>>> def main() -> 'OrderedDict[str, str]':
...     x: OrderedDict[str, str] = OrderedDict()
...     print(x)
...     return x
...
>>>

但是你可以使用from __future__ import annotations来避免它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多