简体   繁体   中英

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

In Python 3 you can add descriptions to your function parameters:

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

and you can also provide an expected type which can later be checked with mypy :

def foo(host: str)
    cool_stuff()

Both are very useful in my eyes - is there a way to combine both and still be able to let mypy check consistency?

Nope, that's partially why PEP 484 was written, to offer a clear and sole use of function annotations, type-hints.

Specifically in the section about existing uses , it states:

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 .

and goes on to state:

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.

Alternatives where specifying both were considered but obviously rejected due to a decrease in code readability:

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.

Allowing both would also beat the point of this PEP and fragment the use of annotations. In the end, your best option is to use good ol' docstrings for documenting parameters and stick to using function annotations solely for type hints.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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