typing.get_type_hints returns 联合而不是可选

typing.get_type_hints returns Union instead of Optional

我正在尝试从 Python 函数中提取一些很好的人类可读类型提示,但是 typing.get_type_hints() 返回的内容比我预期的 complex/less 更易读。

例如:

import typing

def say_something(something: str = None):
     print(something)

typing.get_type_hints(say_something)

想要它给我的是:

{'something': Optional[str]}

according to the docs,这确实是应该发生的事情:

If necessary, Optional[t] is added for function and method annotations if a default value equal to None is set.

实际上 returns是这样的,它是等价的,但可读性较差:

{'something': typing.Union[str, NoneType]}

除了手动将 typing.Union[{x}, NoneType] 替换为 Optional[{x}] 之外,还有什么方法可以在 Python 3 中获得这些更好的类型提示吗? (我特别在 3.7.5 上。)

AFAIK Optional[smth] 将始终 return Union[smth, NoneType],所以基本上没有单独的 Optional 类型注释,它只是一个 alias/shorthand.

如果我们看一下 typing module source

https://github.com/python/cpython/blob/df8913f7c48d267efd662e8ffd9496595115eee8/Lib/typing.py#L369-L371

我们可以看到,当我们调用 Optional[smth] 时,得到 returned 的是 Union[smth, NoneType]

我们也可以在 REPL 中检查这个

>>> from typing import Optional
>>> Optional[str]
typing.Union[str, NoneType]