Python type hints
What is Python type hint?
Optional “type hints” (also called “type annotations”), special syntax that
allow declaring the type of objects. By declaring types for your variables,
editors and tools can give you better support and analyze your code. Type hints
normally don’t affect the runtime behavior of your code.
Python has rich typing support, we can check related Typing PEPs.
In this note I collect some of the most important features, recipes related to type hints. Initial information is from FastAPI python types intro.
Basic examples
Initial code snippets, without any types:
Rewritten with type hints:
Type hints help us to analyze code better, in following example we get type hint warning, ’■ Operator ”+” not supported for types “str” and “int”‘:
Python types and type hints
We can use following basic types:
int
- integerfloat
- floating point numberstr
- stringbool
- boolean
There are some data structures that can contain other values, like dict
,
list
, set
and tuple
. And the internal values can have their own type too
(list(int)
). These types that have internal types are called "generic"
types. And it’s possible to declare them, with optional internal types.
Python standard module typing
provide runtime support for these type hints,
but newer Python version can make this obsolete.
As Python advances, newer versions come with improved support for these type
annotations and in many cases you won’t even need to import and use the typing
module to declare the type annotations.
List type
We can declare variable type as list of integers with following syntax:
variable_name: list[int]
, in the brackets are type parameters. Usage in the
function: