Python 3 中可以结合参数描述和类型提示吗?

Is combining argument descriptions and type hinting possible in Python 3?

在Python3中你可以为你的函数参数添加描述:

def foo(host: 'ip address for connection')
    cool_stuff()

你还可以提供一个预期的类型,稍后可以用 mypy:

检查
def foo(host: str)
    cool_stuff()

在我看来两者都非常有用 - 有没有办法将两者结合起来并且仍然能够让 mypy 检查一致性?

不,这就是编写 PEP 484 的部分原因,以提供函数注释和类型提示的清晰且唯一的用途。

具体在 section about existing uses 中,它指出:

One line of argument points out that PEP 3107 explicitly supports the use of arbitrary expressions in function annotations. The new proposal is then considered incompatible with the specification of PEP 3107 .

并继续说明:

We do hope that type hints will eventually become the sole use for annotations, but this will require additional discussion and a deprecation period after the initial roll-out of the typing module with Python.

考虑了同时指定两者的备选方案,但由于代码可读性下降而明显被拒绝:

Despite all these options, proposals have been circulated to allow type hints and other forms of annotations to coexist for individual arguments. One proposal suggests that if an annotation for a given argument is a dictionary literal, each key represents a different form of annotation, and the key 'type' would be use for type hints. The problem with this idea and its variants is that the notation becomes very "noisy" and hard to read.

同时允许这两者也将超出此 PEP 的重点并破坏注释的使用。最后,您最好的选择是使用好的 ol' 文档字符串来记录参数,并坚持仅将函数注释用于类型提示。