Skip to content

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 are int type
  • func returns int type

Lists / Dicts

def process(items: list[int]):
    pass
  • items is a list of int type
def process(items: dict[str, int]):
    pass
  • items is a dict with str keys and int values

Optional

from typing import Optional

def process(a: int, b: Optional[int] = 0):
    pass
  • b is optional and defaults to 0

Union

from typing import Union

def process(a: Union[int, str]):
    pass
  • a can be int or str type

Function Outputs

Return Values

def process() -> list[int]:
    return [1, 2, 3]
  • process returns a list of int type
def process() -> tuple[str, int]:
    return 'a', 1
  • process returns a tuple of str and int type

Return None

def process() -> None:
    pass
  • process returns None

Classes

Class Attributes

class A:
    def __init__(self, a: int):
        self.a = a

def process(a: A):
    pass