Type Parameter Syntax (3.12+)
PY · Modern Featuressyntax
def func[T](arg: T) -> T: ...
class Name[T]: ...example
# New syntax (3.12+) - no more TypeVar boilerplate
def first_element[T](items: list[T]) -> T:
return items[0]
print(first_element([10, 20, 30]))
print(first_element(["a", "b"]))
# Generic class
class Pair[A, B]:
def __init__(self, left: A, right: B):
self.left = left
self.right = right
p = Pair("name", 42)
print(p.left, p.right)output
10
a
name 42Note The [T] syntax on def/class replaces manual TypeVar declarations. It is scoped to the function or class, unlike module-level TypeVar which could be reused accidentally.