Pycon NL: typing your python code like a ninja - Thiago Bellini Ribeiro

Tags: python, pycon, django

(One of my summaries of the Pycon NL one-day conference in Utrecht, NL).

By now, the basics of python type hints are well known:

def something(x: int) -> float:
    ...

def get_person(name: str, age: int|None) -> Person:
    ...

Note: I’ve tried typing (…) fast enough, but my examples will probably have errors in them, so check the typing documentation! His slides are here so do check those :-)

Sometimes you can have multiple types for some input. Often the output also changes then. You can accept both import types and suggest both output types, but with @overload you can be more specific:

from typing import overload

@overload
def something(x: str) -> str:
    ...

def something(x: int) -> int:
    ...

Tyou can do the same with a generic:

from typing import TypeVar

T = TypeVar("T")

@overload
def something(x: T) -> T:
    ...

# New syntax
def something[T](x: T) -> T:
    ...

# Same, but restricted to two types
def something[T: str|int](x: T) -> T:
    ...

Generic classes can be handy for, for instance, django:

class ModelManager[T: Model]:
    def __init__(self, model_class: type[T]) -> None:
        ....

    def get(self, pk: int) -> T:
        ...

Type narrowing. Sometimes you accept a broad range of items, but if you return True, it means the input is of a specific type:

from typing import TypeGuard

def is_user(obj: Any) -> TypeGuard[User]:
    ....

def something(obj: Any):
    if is_user(obj):
        # From here on, typing knows obj is a User

Generic **kwargs are a challenge, but there’s support for it:

from typing import TypedDict, Required, Unpack

class SomethingArgs(TypedDict, total-False):
    usernanme: Required(str)
    age: int

def something(**kwargs: Unpack[SomethingArgs]):
    ...

If you return “self” from some class method, you run into problems with subclasses, as normally the method says it returns the parent class. You can use from typing import Self` and return the type ``Self instead.

Nice talk, I learned quite a few new tricks!

https://reinout.vanrees.org/images/2025/austria-vacation-2.jpeg

Unrelated photo from our 2025 holiday in Austria: church of Neufelden seen on the top of the hill.

 
vanrees.org logo

Reinout van Rees

My name is Reinout van Rees and I program in Python, I live in the Netherlands, I cycle recumbent bikes and I have a model railway.

Weblog feeds

Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):