frans frans - 1 month ago 11
Python Question

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')

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

def foo(host: str)

Both are very useful in my eyes - is there a way to combine both and still be able to let
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.