Full documentation is here.
Type annotations do not affect runtime, but allow other tools to statically analyse you code for errors. The offical checker is MyPy, which has an IntelliJ extension.
Type annotations come after the variable/attribute declaration (unlike Java):
foo: int
foo = 1
They can be inline:
bar: int = 1
They can define the signature of functions:
def half(value: int) -> float:
return value / 2
The typing module also exposes helpers for more complex annotations:
from typing import Any, Dict, Union
foo: Union[int, float] = 1 # `foo` can be an int or a float
dictionary: Dict[str, Any] = {"foo": 1, "bar": 2} # dictionary is a `dict`, with string keys and values of any type
You can also annotate classes, and use them as annotations themselves:
class Foo:
pass
class Bar:
x: Foo # This says that instances of Bar should have an attribute `x` of type `Foo`
Type checkers can tell you if something is wrong, without running your code:
def foo(value: Union[str, None] = None) -> List[str]:
return value.split("\n")
MyPy will show Item "None" of "Union[str, None]" has no attribute name "split"
for the above code.
With the editor extension, this will be highlighted as soon as you type it!
Useful and concise. Thank you