Declare Modern Type Parameters and Defaults
Core idea
Python 3.12 introduced scoped type parameters using brackets after a function, class or type alias name. Python 3.13 added defaults for type parameters. A default is a static type fallback, not a default function argument or a runtime conversion. Explicit type arguments override a class parameter default.
def echo[T](value:T)->T: return valueprint(echo('ready'),echo(7))print(echo.__type_params__[0].__name__)T is declared by the function header, not a module-level assignment.
Provide a generic class default
class Bucket[T = str]: def __init__(self, value:T|None=None): self.value=valueprint(Bucket.__type_params__[0].__default__.__name__)print(Bucket[int](6).value)The default type is str; the explicit int specialization is allowed. The initializer separately defaults its value to None.
Common mistake
Bracket declarations fail to parse before 3.12; defaults require 3.13. A type default cannot make missing runtime values appear.
Practice
Define a generic class with a default parameter and compare a bare annotation with an explicit specialization in a checker.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Modern type parameters and defaults
Check your understanding of modern type parameters and defaults.
What is printed?
def identity[T](x:T)->T: return xprint(identity(11))What is printed?
class Box[T=int]: passprint(Box.__type_params__[0].__default__.__name__)What version introduces bracket type parameters?
What version adds type parameter defaults?