1

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:
    ...
0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.