Python Typing¶
Simple typing syntax for Python variables, functions and classes with the typing
library.
from typing import ...
Note
For more specific data validation, use Pydantic models.
pip install pydantic
Function Inputs¶
Easy Usage
def add(a: int, b: int) -> int:
return a + b
a
,b
areint
typefunc
returnsint
type
Lists / Dicts
def process(items: list[int]):
pass
items
is alist
ofint
type
def process(items: dict[str, int]):
pass
items
is adict
withstr
keys andint
values
Optional
from typing import Optional
def process(a: int, b: Optional[int] = 0):
pass
b
is optional and defaults to0
Union
from typing import Union
def process(a: Union[int, str]):
pass
a
can beint
orstr
type
Function Outputs¶
Return Values
def process() -> list[int]:
return [1, 2, 3]
process
returns alist
ofint
type
def process() -> tuple[str, int]:
return 'a', 1
process
returns atuple
ofstr
andint
type
Return None
def process() -> None:
pass
process
returnsNone
Classes¶
Class Attributes
class A:
def __init__(self, a: int):
self.a = a
def process(a: A):
pass