Menu

Levels of Python type annotations
🖼️

Levels of Python type annotations

DEV Community·Aaron Maxwell·6 months ago
#1TxwOKzT
#coding#documentation#programming#python#type
Reading 0:00
15s threshold

Python has optional type annotations - also called "type hints". Like this:

def entry_to_dict ( entry : Entry ) -> dict : return { ' title ' : entry . title , ' num_likes ' : entry . num_likes , ' url ' : entry . url , }

Enter fullscreen mode

Exit fullscreen mode

The annotations here being "Entry" as the type for the "entry" argument, and "dict" as the return type.

In fact, there are at least 3 ways type annotations can be used:

documentation

to configure libraries and tools

static type checking

These are so different, asking "do you use type annotations?" is really too vague. It's three separate questions.

The first is demonstrated by entry_to_dict() above. You are reading the code, and just by reading it, you know that entry should be an instance of a class called Entry, and entry_to_dict() should return a dictionary.

This by itself is really useful. And part of what makes it useful is how easy it is to include when you write the code.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.