简体   繁体   English

Python:未知类型提示不会因__future__ import引发异常

[英]Python: Unknown type hint does not raise exception with __future__ import

All classes need to be defined before they can be used as a type hint. 必须先定义所有类,然后才能将其用作类型提示。 To get around it in some scenarios, the __future__ import is recommended . 为了在某​​些情况下解决该问题, 建议使用__future__ import。 That's why the following code works fine (in Python 3.7): 这就是以下代码可以正常工作的原因(在Python 3.7中):

from __future__ import annotations


class Person:
    def get_relative(name: str) -> Person:
        ...

Without the __future__ import it would raise a NameError . 没有__future__导入,它将引发NameError But this code works fine too: 但是这段代码也可以正常工作:

from __future__ import annotations


class Person:
    def get_relative(name: BlahBlahTypoWhatever) -> Person:
        ...

I expected something like NameError: name 'BlahBlahTypoWhatever' is not defined . 我期望类似NameError: name 'BlahBlahTypoWhatever' is not defined东西NameError: name 'BlahBlahTypoWhatever' is not defined Is this an expected behavior? 这是预期的行为吗?

Python itself does no type checking whatsoever, so it won't raise any error about wrong types. Python本身不进行任何类型检查,因此不会引发有关错误类型的任何错误。

The annotations future is simply implicitly changing all annotations to strings, ie this is equivalent: annotations未来只是将所有注释隐式更改为字符串,即等效:

from __future__ import annotations

def foo(bar: Baz): pass
def foo(bar: 'Baz'): pass

Since your annotation is a string now, and Python doesn't do anything with it, there's absolutely no resolution of that name going on at any point, so it doesn't raise any errors. 由于您的注释现在是字符串,而Python对此不做任何事情,因此绝对不会在任何时候对该名称进行任何解析,因此不会引起任何错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM