pythongenericspython-typing

Python 3.12+ generic syntax for <T extends Foo>


Python 3.12 introduced new syntax sugar for generics. What's the new way of writing an upper-bounded generic like this:

def foo[T extends Bar](baz: T) -> T:
    ...

Before new syntax features I believe you could write

from typing import Generic, TypeVar

T = TypeVar("T", bound=Bar)

def foo(baz: T) -> T:
    ...

Solution

  • 3.12+ type parameter list syntax allows for upper-bounding with the Type: Supertype pattern:

    def foo[T: Bar](baz: T) -> T:
        ...
    

    This is roughly equivalent to setting the bound parameter on a TypeVar.