from collections.abc import Callable
def apply(
values: list[int],
transform: Callable[[int], int]
) -> list[int]:
return [transform(v) for v invalues]
result = apply([1, 2, 3], lambda x: x * 10)
print(result)
output
[10, 20, 30]
Note Use collections.abc.Callable for function type hints. The format is Callable[[ArgTypes], ReturnType]. For complex signatures, consider typing.Protocol.
# New syntax (3.12+) - no more TypeVar boilerplatedef first_element[T](items: list[T]) -> T:
return items[0]
print(first_element([10, 20, 30]))
print(first_element(["a", "b"]))
# Generic classclass 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 42
Note 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.
// TypeScript infers T from the argument — no need to specify it manually
Note Type parameters are inferred from arguments in most cases. Only specify them explicitly when inference gives the wrong type. In .tsx files, arrow generics need a trailing comma: <T,>(param: T) to avoid JSX ambiguity.