On this page
typing.Generic
Prev: typing.Generator | Up: typing | Next: typing.get_args
Rel: typing.AbstractSet, typing.Annotated, typing.Any, typing.assert_never
Ref: docs.python.org — typing.Generic
Tags: #public #python3 #stdlib #typing
Import
import typing
from typing import Generic
Signature & Overview
typing.Generic()
Abstract base class for generic types.
Usage
from typing import Generic, TypeVar
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, value: T) -> None:
self.value = value
b: Box[int] = Box(42)
assert b.value == 42
Gotchas
- Python 3.12+ shorthand: You can write
class Box[T]:directly without importingGenericorTypeVar.
REPL Inspect
from typing import Generic
help(Generic)
Linked from
Related notes
- tuts/python3/stdlib_module/typing/Generator Linked here; links to this page; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/get_args Linked here; links to this page; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/typing/AbstractSet Linked here; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/Annotated Linked here; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/Any Linked here; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/assert_never Linked here; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/assert_type shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/AsyncContextManager shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/AsyncGenerator shared tags: #stdlib, #typing