Skip to content
Advertisement

Python: use Type Hints together with Annotations

In Python, we all know Type hints, which became available from 2015:

JavaScript

and we also know Function Annotations, in particular here I am referring to textual annotations like:

JavaScript

But is it possible to use Type Hints together with a textual function annotation?

For example:

JavaScript

This last one throws an error.

I cannot seem to find any source in PEP or Python docs about whether this would be possible or not. Although I haven’t searched particularly deeply, I still would appreciate a source on potential answers.

Advertisement

Answer

Like Samwise said, type checkers will not understand if the annotation is a tuple of the type and description (or whatever other metadata you wish to attach). PEP 593 – Flexible function and variable annotations addresses exactly this via the following:

JavaScript

The reason we introduce a wrapper class Description is so it’s clear that the written string is intended to be a description consumed by us, and so other libraries that analyze annotations do not get confused in case they use str for their own metadata.

Then, per typing.Annotated, you can use typing.get_type_hints(name, include_extras=True) to get the description at runtime.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement