Welcome to typing_extensions’s documentation!

typing_extensions complements the standard-library typing module, providing runtime support for type hints as specified by PEP 484 and subsequent PEPs. The module serves two related purposes:

  • Enable use of new type system features on older Python versions. For example, typing.TypeGuard is new in Python 3.10, but typing_extensions allows users on previous Python versions to use it too.

  • Enable experimentation with type system features proposed in new PEPs before they are accepted and added to the typing module.

New features may be added to typing_extensions as soon as they are specified in a PEP that has been added to the python/peps repository. If the PEP is accepted, the feature will then be added to the typing module for the next CPython release. No typing PEP that affected typing_extensions has been rejected so far, so we haven’t yet figured out how to deal with that possibility.

Bugfixes and new typing features that don’t require a PEP may be added to typing_extensions once they are merged into CPython’s main branch.

typing_extensions also re-exports all names from the typing module, including those that have always been present in the module. This allows users to import names from typing_extensions without having to remember exactly when each object was added to typing. There are a few exceptions: typing.ByteString, which is deprecated and due to be removed in Python 3.14, is not re-exported. Similarly, the typing.io and typing.re submodules, which are removed in Python 3.13, are excluded.

Versioning and backwards compatibility

Starting with version 4.0.0, typing_extensions uses Semantic Versioning. A changelog is maintained on GitHub.

The major version is incremented for all backwards-incompatible changes. Therefore, it’s safe to depend on typing_extensions like this: typing_extensions >=x.y, <(x+1), where x.y is the first version that includes all features you need. In view of the wide usage of typing_extensions across the ecosystem, we are highly hesitant to break backwards compatibility, and we do not expect to increase the major version number in the foreseeable future.

Feature releases, with version numbers of the form 4.N.0, are made at irregular intervals when enough new features accumulate. Before a feature release, at least one release candidate (with a version number of the form 4.N.0rc1) should be released to give downstream users time to test. After at least a week of testing, the new feature version may then be released. If necessary, additional release candidates can be added.

Bugfix releases, with version numbers of the form 4.N.1 or higher, may be made if bugs are discovered after a feature release.

We provide no backward compatibility guarantees for prereleases (e.g., release candidates) and for unreleased code in our Git repository.

Before version 4.0.0, the versioning scheme loosely followed the Python version from which features were backported; for example, typing_extensions 3.10.0.0 was meant to reflect typing as of Python 3.10.0. During this period, no changelog was maintained.

Runtime use of types

We aim for complete backwards compatibility in terms of the names we export: code like from typing_extensions import X that works on one typing-extensions release will continue to work on the next. It is more difficult to maintain compatibility for users that introspect types at runtime, as almost any detail can potentially break compatibility. Users who introspect types should follow these guidelines to minimize the risk of compatibility issues:

  • Always check for both the typing and typing_extensions versions of objects, even if they are currently the same on some Python version. Future typing_extensions releases may re-export a separate version of the object to backport some new feature or bugfix.

  • Use public APIs like get_origin() and get_original_bases() to access internal information about types, instead of accessing private attributes directly. If some information is not available through a public attribute, consider opening an issue in CPython to add such an API.

Here is an example recipe for a general-purpose function that could be used for reasonably performant runtime introspection of typing objects. The function will be resilient against any potential changes in typing_extensions that alter whether an object is reimplemented in typing_extensions, rather than simply being re-exported from the typing module:

import functools
import typing
import typing_extensions
from typing import Tuple, Any

# Use an unbounded cache for this function, for optimal performance
@functools.lru_cache(maxsize=None)
def get_typing_objects_by_name_of(name: str) -> Tuple[Any, ...]:
    result = tuple(
        getattr(module, name)
        # You could potentially also include mypy_extensions here,
        # if your library supports mypy_extensions
        for module in (typing, typing_extensions)
        if hasattr(module, name)
    )
    if not result:
        raise ValueError(
            f"Neither typing nor typing_extensions has an object called {name!r}"
        )
    return result


# Use a cache here as well, but make it a bounded cache
# (the default cache size is 128)
@functools.lru_cache()
def is_typing_name(obj: object, name: str) -> bool:
    return any(obj is thing for thing in get_typing_objects_by_name_of(name))

Example usage:

>>> import typing, typing_extensions
>>> from functools import partial
>>> from typing_extensions import get_origin
>>> is_literal = partial(is_typing_name, name="Literal")
>>> is_literal(typing.Literal)
True
>>> is_literal(typing_extensions.Literal)
True
>>> is_literal(typing.Any)
False
>>> is_literal(get_origin(typing.Literal[42]))
True
>>> is_literal(get_origin(typing_extensions.Final[42]))
False

Python version support

typing_extensions currently supports Python versions 3.8 and higher. In the future, support for older Python versions will be dropped some time after that version reaches end of life.

Module contents

As most of the features in typing_extensions exist in typing in newer versions of Python, the documentation here is brief and focuses on aspects that are specific to typing_extensions, such as limitations on specific Python versions.

Special typing primitives

Annotated

See typing.Annotated and PEP 593. In typing since 3.9.

Changed in version 4.1.0: Annotated can now wrap ClassVar and Final.

Any

See typing.Any.

Since Python 3.11, typing.Any can be used as a base class. typing_extensions.Any supports this feature on older versions.

New in version 4.4.0: Added to support inheritance from Any.

Concatenate

See typing.Concatenate and PEP 612. In typing since 3.10.

The backport does not support certain operations involving ... as a parameter; see issue #48 and issue #110 for details.

Final

See typing.Final and PEP 591. In typing since 3.8.

Literal

See typing.Literal and PEP 586. In typing since 3.8.

typing.Literal does not flatten or deduplicate parameters on Python <3.9.1, and a caching bug was fixed in 3.10.1/3.9.8. The typing_extensions version flattens and deduplicates parameters on all Python versions, and the caching bug is also fixed on all versions.

Changed in version 4.6.0: Backported the bug fixes from CPython PR #29334, CPython PR #23294, and CPython PR #23383.

LiteralString

See typing.LiteralString and PEP 675. In typing since 3.11.

New in version 4.1.0.

class NamedTuple

See typing.NamedTuple.

typing_extensions backports several changes to NamedTuple on Python 3.11 and lower: in 3.11, support for generic NamedTuples was added, and in 3.12, the __orig_bases__ attribute was added.

New in version 4.3.0: Added to provide support for generic NamedTuples.

Changed in version 4.6.0: Support for the __orig_bases__ attribute was added.

Changed in version 4.7.0: The undocumented keyword argument syntax for creating NamedTuple classes (NT = NamedTuple("NT", x=int)) is deprecated, and will be disallowed in Python 3.15. Use the class-based syntax or the functional syntax instead.

Changed in version 4.7.0: When using the functional syntax to create a NamedTuple class, failing to pass a value to the ‘fields’ parameter (NT = NamedTuple("NT")) is deprecated. Passing None to the ‘fields’ parameter (NT = NamedTuple("NT", None)) is also deprecated. Both will be disallowed in Python 3.15. To create a NamedTuple class with zero fields, use class NT(NamedTuple): pass or NT = NamedTuple("NT", []).

Never

See typing.Never. In typing since 3.11.

New in version 4.1.0.

class NewType(name, tp)

See typing.NewType. In typing since 3.5.2.

Instances of NewType were made picklable in 3.10 and an error message was improved in 3.11; typing_extensions backports these changes.

Changed in version 4.6.0: The improvements from Python 3.10 and 3.11 were backported.

NotRequired

See typing.NotRequired and PEP 655. In typing since 3.11.

New in version 4.0.0.

class ParamSpec(name, *, default=...)

See typing.ParamSpec and PEP 612. In typing since 3.10.

The typing_extensions version adds support for the default= argument from PEP 696.

On older Python versions, typing_extensions.ParamSpec may not work correctly with introspection tools like get_args() and get_origin(). Certain special cases in user-defined typing.Generics are also not available (e.g., see issue #126).

Changed in version 4.4.0: Added support for the default= argument.

Changed in version 4.6.0: The implementation was changed for compatibility with Python 3.12.

Changed in version 4.8.0: Passing an ellipsis literal (...) to default now works on Python 3.10 and lower.

class ParamSpecArgs
class ParamSpecKwargs

See typing.ParamSpecArgs and typing.ParamSpecKwargs. In typing since 3.10.

class Protocol

See typing.Protocol and PEP 544. In typing since 3.8.

Python 3.12 improves the performance of runtime-checkable protocols; typing_extensions backports this improvement.

Changed in version 4.6.0: Backported the ability to define __init__ methods on Protocol classes.

Changed in version 4.6.0: Backported changes to runtime-checkable protocols from Python 3.12, including CPython PR #103034 and CPython PR #26067.

Changed in version 4.7.0: Classes can now inherit from both typing.Protocol and typing_extensions.Protocol simultaneously. Previously, this led to TypeError being raised due to a metaclass conflict.

It is recommended to avoid doing this if possible. Not all features and bugfixes that typing_extensions.Protocol backports from newer Python versions are guaranteed to work if typing.Protocol is also present in a protocol class’s method resolution order. See issue #245 for some examples.

ReadOnly

See PEP 705. Indicates that a TypedDict item may not be modified.

New in version 4.9.0.

Required

See typing.Required and PEP 655. In typing since 3.11.

New in version 4.0.0.

Self

See typing.Self and PEP 673. In typing since 3.11.

New in version 4.0.0.

TypeAlias

See typing.TypeAlias and PEP 613. In typing since 3.10.

class TypeAliasType(name, value, *, type_params=())

See typing.TypeAliasType and PEP 695. In typing since 3.12.

New in version 4.6.0.

TypeGuard

See typing.TypeGuard and PEP 647. In typing since 3.10.

TypeIs

See PEP 742. Similar to TypeGuard, but allows more type narrowing.

New in version 4.10.0.

class TypedDict(dict, total=True)

See typing.TypedDict and PEP 589. In typing since 3.8.

typing_extensions backports various bug fixes and improvements to TypedDict on Python 3.11 and lower. TypedDict does not store runtime information about which (if any) keys are non-required in Python 3.8, and does not honor the total keyword with old-style TypedDict() in Python 3.9.0 and 3.9.1. typing.TypedDict also does not support multiple inheritance with typing.Generic on Python <3.11, and typing.TypedDict classes do not consistently have the __orig_bases__ attribute on Python <3.12. The typing_extensions backport provides all of these features and bugfixes on all Python versions.

Historically, TypedDict has supported an alternative creation syntax where the fields are supplied as keyword arguments (e.g., TypedDict("TD", a=int, b=str)). In CPython, this feature was deprecated in Python 3.11 and removed in Python 3.13. typing_extensions.TypedDict raises a DeprecationWarning when this syntax is used in Python 3.12 or lower and fails with a TypeError in Python 3.13 and higher.

typing_extensions supports the experimental ReadOnly qualifier proposed by PEP 705. It is reflected in the following attributes:

__readonly_keys__

A frozenset containing the names of all read-only keys. Keys are read-only if they carry the ReadOnly qualifier.

New in version 4.9.0.

__mutable_keys__

A frozenset containing the names of all mutable keys. Keys are mutable if they do not carry the ReadOnly qualifier.

New in version 4.9.0.

The experimental closed keyword argument and the special key __extra_items__ proposed in PEP 728 are supported.

When closed is unspecified or closed=False is given, __extra_items__ behaves like a regular key. Otherwise, this becomes a special key that does not show up in __readonly_keys__, __mutable_keys__, __required_keys__, __optional_keys, or __annotations__.

For runtime introspection, two attributes can be looked at:

__closed__

A boolean flag indicating whether the current TypedDict is considered closed. This is not inherited by the TypedDict’s subclasses.

New in version 4.10.0.

__extra_items__

The type annotation of the extra items allowed on the TypedDict. This attribute defaults to None on a TypedDict that has itself and all its bases non-closed. This default is different from type(None) that represents __extra_items__: None defined on a closed TypedDict.

If __extra_items__ is not defined or inherited on a closed TypedDict, this defaults to Never.

New in version 4.10.0.

Changed in version 4.3.0: Added support for generic TypedDicts.

Changed in version 4.6.0: A DeprecationWarning is now emitted when a call-based TypedDict is constructed using keyword arguments.

Changed in version 4.6.0: Support for the __orig_bases__ attribute was added.

Changed in version 4.7.0: TypedDict is now a function rather than a class. This brings typing_extensions.TypedDict closer to the implementation of typing.TypedDict on Python 3.9 and higher.

Changed in version 4.7.0: When using the functional syntax to create a TypedDict class, failing to pass a value to the ‘fields’ parameter (TD = TypedDict("TD")) is deprecated. Passing None to the ‘fields’ parameter (TD = TypedDict("TD", None)) is also deprecated. Both will be disallowed in Python 3.15. To create a TypedDict class with 0 fields, use class TD(TypedDict): pass or TD = TypedDict("TD", {}).

Changed in version 4.9.0: Support for the ReadOnly qualifier was added.

Changed in version 4.10.0: The keyword argument closed and the special key __extra_items__ when closed=True is given were supported.

TypeVar(name, *constraints, bound=None, covariant=False,
contravariant=False, infer_variance=False, default=...)

See typing.TypeVar.

The typing_extensions version adds support for the default= argument from PEP 696, as well as the infer_variance= argument from PEP 695 (also available in Python 3.12).

New in version 4.4.0: Added in order to support the new default= and infer_variance= arguments.

Changed in version 4.6.0: The implementation was changed for compatibility with Python 3.12.

class TypeVarTuple(name, *, default=...)

See typing.TypeVarTuple and PEP 646. In typing since 3.11.

The typing_extensions version adds support for the default= argument from PEP 696.

New in version 4.1.0.

Changed in version 4.4.0: Added support for the default= argument.

Changed in version 4.6.0: The implementation was changed for compatibility with Python 3.12.

Unpack

See typing.Unpack and PEP 646. In typing since 3.11.

In Python 3.12, the repr() was changed as a result of PEP 692. typing_extensions backports this change.

Generic type aliases involving Unpack may not work correctly on Python 3.10 and lower; see issue #103 for details.

New in version 4.1.0.

Changed in version 4.6.0: Backport repr() changes from Python 3.12.

Abstract Base Classes

class Buffer

See collections.abc.Buffer. Added to the standard library in Python 3.12.

New in version 4.6.0.

Protocols

class SupportsAbs

See typing.SupportsAbs.

typing_extensions backports a more performant version of this protocol on Python 3.11 and lower.

New in version 4.6.0.

class SupportsBytes

See typing.SupportsBytes.

typing_extensions backports a more performant version of this protocol on Python 3.11 and lower.

New in version 4.6.0.

class SupportsComplex

See typing.SupportsComplex.

typing_extensions backports a more performant version of this protocol on Python 3.11 and lower.

New in version 4.6.0.

class SupportsFloat

See typing.SupportsFloat.

typing_extensions backports a more performant version of this protocol on Python 3.11 and lower.

New in version 4.6.0.

class SupportsIndex

See typing.SupportsIndex. In typing since 3.8.

typing_extensions backports a more performant version of this protocol on Python 3.11 and lower.

Changed in version 4.6.0: Backported the performance improvements from Python 3.12.

class SupportsInt

See typing.SupportsInt.

typing_extensions backports a more performant version of this protocol on Python 3.11 and lower.

New in version 4.6.0.

class SupportsRound

See typing.SupportsRound.

typing_extensions backports a more performant version of this protocol on Python 3.11 and lower.

New in version 4.6.0.

Decorators

dataclass_transform(*, eq_default=False, order_default=False,
kw_only_default=False, frozen_default=False,
field_specifiers=(), **kwargs)

See typing.dataclass_transform() and PEP 681. In typing since 3.11.

Python 3.12 adds the frozen_default parameter; typing_extensions backports this parameter.

New in version 4.1.0.

Changed in version 4.2.0: The field_descriptors parameter was renamed to field_specifiers. For compatibility, the decorator now accepts arbitrary keyword arguments.

Changed in version 4.5.0: The frozen_default parameter was added.

@deprecated(msg, *, category=DeprecationWarning, stacklevel=1)

See PEP 702. In the warnings module since Python 3.13.

New in version 4.5.0.

Changed in version 4.9.0: Inheriting from a deprecated class now also raises a runtime DeprecationWarning.

@final

See typing.final() and PEP 591. In typing since 3.8.

Since Python 3.11, this decorator supports runtime introspection by setting the __final__ attribute wherever possible; typing_extensions.final backports this feature.

Changed in version 4.1.0: The decorator now attempts to set the __final__ attribute on decorated objects.

@overload

See typing.overload().

Since Python 3.11, this decorator supports runtime introspection through get_overloads(); typing_extensions.overload backports this feature.

Changed in version 4.2.0: Introspection support via get_overloads() was added.

@override

See typing.override() and PEP 698. In typing since 3.12.

New in version 4.4.0.

Changed in version 4.5.0: The decorator now attempts to set the __override__ attribute on the decorated object.

@runtime_checkable

See typing.runtime_checkable(). In typing since 3.8.

In Python 3.12, the performance of runtime-checkable protocols was improved, and typing_extensions backports these performance improvements.

Functions

assert_never(arg)

See typing.assert_never(). In typing since 3.11.

New in version 4.1.0.

assert_type(val, typ)

See typing.assert_type(). In typing since 3.11.

New in version 4.2.0.

clear_overloads()

See typing.clear_overloads(). In typing since 3.11.

New in version 4.2.0.

get_args(tp)

See typing.get_args(). In typing since 3.8.

This function was changed in 3.9 and 3.10 to deal with Annotated and ParamSpec correctly; typing_extensions backports these fixes.

get_origin(tp)

See typing.get_origin(). In typing since 3.8.

This function was changed in 3.9 and 3.10 to deal with Annotated and ParamSpec correctly; typing_extensions backports these fixes.

get_original_bases(cls)

See types.get_original_bases(). Added to the standard library in Python 3.12.

This function should always produce correct results when called on classes constructed using features from typing_extensions. However, it may produce incorrect results when called on some NamedTuple or TypedDict classes on Python <=3.11.

New in version 4.6.0.

get_overloads(func)

See typing.get_overloads(). In typing since 3.11.

Before Python 3.11, this works only with overloads created through overload(), not with typing.overload().

New in version 4.2.0.

get_protocol_members(tp)

Return the set of members defined in a Protocol. This works with protocols defined using either typing.Protocol or typing_extensions.Protocol.

>>> from typing_extensions import Protocol, get_protocol_members
>>> class P(Protocol):
...     def a(self) -> str: ...
...     b: int
>>> get_protocol_members(P)
frozenset({'a', 'b'})

Raise TypeError for arguments that are not Protocols.

New in version 4.7.0.

get_type_hints(obj, globalns=None, localns=None, include_extras=False)

See typing.get_type_hints().

In Python 3.11, this function was changed to support the new typing.Required and typing.NotRequired. typing_extensions backports these fixes.

Changed in version 4.1.0: Interaction with Required and NotRequired.

is_protocol(tp)

Determine if a type is a Protocol. This works with protocols defined using either typing.Protocol or typing_extensions.Protocol.

For example:

class P(Protocol):
    def a(self) -> str: ...
    b: int

is_protocol(P)    # => True
is_protocol(int)  # => False

New in version 4.7.0.

is_typeddict(tp)

See typing.is_typeddict(). In typing since 3.10.

On versions where TypedDict is not the same as typing.TypedDict, this function recognizes TypedDict classes created through either mechanism.

New in version 4.1.0.

Changed in version 4.7.0: is_typeddict() now returns False when called with TypedDict itself as the argument, consistent with the behavior of typing.is_typeddict().

reveal_type(obj)

See typing.reveal_type(). In typing since 3.11.

New in version 4.1.0.

Annotation metadata

class Doc(documentation, /)

Define the documentation of a type annotation using Annotated, to be used in class attributes, function and method parameters, return values, and variables.

The value should be a positional-only string literal to allow static tools like editors and documentation generators to use it.

This complements docstrings.

The string value passed is available in the attribute documentation.

Example:

>>> from typing_extensions import Annotated, Doc
>>> def hi(to: Annotated[str, Doc("Who to say hi to")]) -> None: ...

New in version 4.8.0: See PEP 727.

documentation

The documentation string passed to Doc.

Pure aliases

These are simply re-exported from the typing module on all supported versions of Python. They are listed here for completeness.

class AbstractSet

See typing.AbstractSet.

New in version 4.7.0.

AnyStr

See typing.AnyStr.

New in version 4.7.0.

class AsyncContextManager

See typing.AsyncContextManager. In typing since 3.5.4 and 3.6.2.

class AsyncGenerator

See typing.AsyncGenerator. In typing since 3.6.1.

class AsyncIterable

See typing.AsyncIterable. In typing since 3.5.2.

class AsyncIterator

See typing.AsyncIterator. In typing since 3.5.2.

class Awaitable

See typing.Awaitable. In typing since 3.5.2.

class BinaryIO

See typing.BinaryIO.

New in version 4.7.0.

Callable

See typing.Callable.

New in version 4.7.0.

class ChainMap

See typing.ChainMap. In typing since 3.5.4 and 3.6.1.

ClassVar

See typing.ClassVar and PEP 526. In typing since 3.5.3.

class Collection

See typing.Collection.

New in version 4.7.0.

class Container

See typing.Container.

New in version 4.7.0.

class ContextManager

See typing.ContextManager. In typing since 3.5.4.

class Coroutine

See typing.Coroutine. In typing since 3.5.3.

class Counter

See typing.Counter. In typing since 3.5.4 and 3.6.1.

class DefaultDict

See typing.DefaultDict. In typing since 3.5.2.

class Deque

See typing.Deque. In typing since 3.5.4 and 3.6.1.

class Dict

See typing.Dict.

New in version 4.7.0.

class ForwardRef

See typing.ForwardRef.

New in version 4.7.0.

class FrozenSet

See typing.FrozenSet.

New in version 4.7.0.

class Generator

See typing.Generator.

New in version 4.7.0.

class Generic

See typing.Generic.

New in version 4.7.0.

class Hashable

See typing.Hashable.

New in version 4.7.0.

class IO

See typing.IO.

New in version 4.7.0.

class ItemsView

See typing.ItemsView.

New in version 4.7.0.

class Iterable

See typing.Iterable.

New in version 4.7.0.

class Iterator

See typing.Iterator.

New in version 4.7.0.

class KeysView

See typing.KeysView.

New in version 4.7.0.

class List

See typing.List.

New in version 4.7.0.

class Mapping

See typing.Mapping.

New in version 4.7.0.

class MappingView

See typing.MappingView.

New in version 4.7.0.

class Match

See typing.Match.

New in version 4.7.0.

class MutableMapping

See typing.MutableMapping.

New in version 4.7.0.

class MutableSequence

See typing.MutableSequence.

New in version 4.7.0.

class MutableSet

See typing.MutableSet.

New in version 4.7.0.

NoReturn

See typing.NoReturn. In typing since 3.5.4 and 3.6.2.

Optional

See typing.Optional.

New in version 4.7.0.

class OrderedDict

See typing.OrderedDict. In typing since 3.7.2.

class Pattern

See typing.Pattern.

New in version 4.7.0.

class Reversible

See typing.Reversible.

New in version 4.7.0.

class Sequence

See typing.Sequence.

New in version 4.7.0.

class Set

See typing.Set.

New in version 4.7.0.

class Sized

See typing.Sized.

New in version 4.7.0.

class Text

See typing.Text. In typing since 3.5.2.

class TextIO

See typing.TextIO.

New in version 4.7.0.

Tuple

See typing.Tuple.

New in version 4.7.0.

class Type

See typing.Type. In typing since 3.5.2.

TYPE_CHECKING

See typing.TYPE_CHECKING. In typing since 3.5.2.

Union

See typing.Union.

New in version 4.7.0.

class ValuesView

See typing.ValuesView.

New in version 4.7.0.

cast()

See typing.cast().

New in version 4.7.0.

@no_type_check

See typing.no_type_check().

New in version 4.7.0.

@no_type_check_decorator

See typing.no_type_check_decorator().

New in version 4.7.0.