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.TypeGuardis new in Python 3.10, buttyping_extensionsallows 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
typingmodule.
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
typingandtyping_extensionsversions of objects, even if they are currently the same on some Python version. Futuretyping_extensionsreleases may re-export a separate version of the object to backport some new feature or bugfix.Use public APIs like
get_origin()andget_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[int]))
False
Python version support¶
typing_extensions currently supports Python versions 3.9 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.Annotatedand PEP 593. Intypingsince 3.9.
- Any¶
See
typing.Any.Since Python 3.11,
typing.Anycan be used as a base class.typing_extensions.Anysupports this feature on older versions.Added in version 4.4.0: Added to support inheritance from
Any.
- Concatenate¶
See
typing.Concatenateand PEP 612. Intypingsince 3.10.The backport does not support certain operations involving
...as a parameter; see issue #48 and PR #481 for details.
- Final¶
See
typing.Finaland PEP 591. Intypingsince 3.8.
- Literal¶
See
typing.Literaland PEP 586. Intypingsince 3.8.typing.Literaldoes not flatten or deduplicate parameters on Python <3.9.1, and a caching bug was fixed in 3.10.1/3.9.8. Thetyping_extensionsversion 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.LiteralStringand PEP 675. Intypingsince 3.11.Added in version 4.1.0.
- class NamedTuple¶
See
typing.NamedTuple.typing_extensionsbackports several changes toNamedTupleon Python 3.11 and lower: in 3.11, support for genericNamedTuples was added, and in 3.12, the__orig_bases__attribute was added.Added 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. PassingNoneto 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, useclass NT(NamedTuple): passorNT = NamedTuple("NT", []).
- Never¶
See
typing.Never. Intypingsince 3.11.Added in version 4.1.0.
- class NewType(name, tp)¶
See
typing.NewType. Intypingsince 3.5.2.Instances of
NewTypewere made picklable in 3.10 and an error message was improved in 3.11;typing_extensionsbackports these changes.Changed in version 4.6.0: The improvements from Python 3.10 and 3.11 were backported.
- NoDefault¶
See
typing.NoDefault. Intypingsince 3.13.Added in version 4.12.0.
- NoExtraItems¶
A sentinel used when the
extra_itemsclass argument toTypedDictis not provided. Intypingsince 3.15.Added in version 4.13.0.
- NotRequired¶
See
typing.NotRequiredand PEP 655. Intypingsince 3.11.Added in version 4.0.0.
- class ParamSpec(name, *, default=NoDefault)¶
See
typing.ParamSpecand PEP 612. Intypingsince 3.10.The
typing_extensionsversion adds support for thedefault=argument from PEP 696.On older Python versions,
typing_extensions.ParamSpecmay not work correctly with introspection tools likeget_args()andget_origin(). Certain special cases in user-definedtyping.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.Changed in version 4.12.0: The
__default__attribute is now set toNoneifdefault=Noneis passed, and toNoDefaultif no value is passed.Previously, passing
Nonewould result in__default__being set totypes.NoneType, and passing no value for the parameter would result in__default__being set toNone.Changed in version 4.12.0: ParamSpecs now have a
has_default()method, for compatibility withtyping.ParamSpecon Python 3.13+.
- class ParamSpecArgs¶
- class ParamSpecKwargs¶
See
typing.ParamSpecArgsandtyping.ParamSpecKwargs. Intypingsince 3.10.
- class Protocol¶
See
typing.Protocoland PEP 544. Intypingsince 3.8.Python 3.12 improves the performance of runtime-checkable protocols;
typing_extensionsbackports 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.Protocolandtyping_extensions.Protocolsimultaneously. Previously, this led toTypeErrorbeing raised due to a metaclass conflict.It is recommended to avoid doing this if possible. Not all features and bugfixes that
typing_extensions.Protocolbackports from newer Python versions are guaranteed to work iftyping.Protocolis also present in a protocol class’s method resolution order. See issue #245 for some examples.
- ReadOnly¶
See
typing.ReadOnlyand PEP 705. Intypingsince 3.13.Indicates that a
TypedDictitem may not be modified.Added in version 4.9.0.
- Required¶
See
typing.Requiredand PEP 655. Intypingsince 3.11.Added in version 4.0.0.
- Self¶
See
typing.Selfand PEP 673. Intypingsince 3.11.Added in version 4.0.0.
- TypeAlias¶
See
typing.TypeAliasand PEP 613. Intypingsince 3.10.
- class TypeAliasType(name, value, *, type_params=())¶
See
typing.TypeAliasTypeand PEP 695. Intypingsince 3.12.Added in version 4.6.0.
- TypeForm¶
See PEP 747. A special form representing the value of a type expression.
Added in version 4.13.0.
- TypeGuard¶
See
typing.TypeGuardand PEP 647. Intypingsince 3.10.
- TypeIs¶
See
typing.TypeIsand PEP 742. Intypingsince 3.13.Similar to
TypeGuard, but allows more type narrowing.Added in version 4.10.0.
- class TypedDict(dict, total=True, closed=False, extra_items=<no extra items>)¶
See
typing.TypedDictand PEP 589. Intypingsince 3.8, but changed and enhanced in several ways since then.typing_extensionsbackports various bug fixes and improvements toTypedDict.TypedDictdoes not store runtime information about which (if any) keys are non-required in Python 3.8, and does not honor thetotalkeyword with old-styleTypedDict()in Python 3.9.0 and 3.9.1.typing.TypedDictalso does not support multiple inheritance withtyping.Genericon Python <3.11, andtyping.TypedDictclasses do not consistently have the__orig_bases__attribute on Python <3.12. Thetyping_extensionsbackport provides all of these features and bugfixes on all Python versions.Historically,
TypedDicthas 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.TypedDictraises aDeprecationWarningwhen this syntax is used in Python 3.12 or lower and fails with aTypeErrorin Python 3.13 and higher.typing_extensionssupports theReadOnlyqualifier introduced by PEP 705. It is reflected in the following attributes:- __readonly_keys__¶
A
frozensetcontaining the names of all read-only keys. Keys are read-only if they carry theReadOnlyqualifier.Added in version 4.9.0.
- __mutable_keys__¶
A
frozensetcontaining the names of all mutable keys. Keys are mutable if they do not carry theReadOnlyqualifier.Added in version 4.9.0.
The
closedandextra_itemskeyword arguments introduced by PEP 728 and supported in Python 3.15 and newer are supported.For runtime introspection, two attributes can be looked at:
- __closed__¶
A boolean flag indicating whether the current
TypedDictis considered closed. This reflects theclosedclass argument.Added in version 4.10.0.
- __extra_items__¶
The type of the extra items allowed on the
TypedDict. This attribute defaults toNoExtraItemsif theextra_itemsclass argument is not provided.Added in version 4.10.0.
Changed in version 4.3.0: Added support for generic
TypedDicts.Changed in version 4.6.0: A
DeprecationWarningis now emitted when a call-basedTypedDictis constructed using keyword arguments.Changed in version 4.6.0: Support for the
__orig_bases__attribute was added.Changed in version 4.7.0:
TypedDictis now a function rather than a class. This bringstyping_extensions.TypedDictcloser to the implementation oftyping.TypedDicton 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. PassingNoneto 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, useclass TD(TypedDict): passorTD = TypedDict("TD", {}).Changed in version 4.9.0: Support for the
ReadOnlyqualifier was added.Changed in version 4.10.0: The keyword argument
closedand the special key__extra_items__whenclosed=Trueis given were supported.Changed in version 4.13.0: PEP 728 support was updated to a newer version. Extra items are now indicated with an
extra_itemsclass argument, not a special key__extra_items__.A value assigned to
__total__in the class body of aTypedDictwill be overwritten by thetotalargument of theTypedDictconstructor.
- TypeVar(name, *constraints, bound=None, covariant=False,
- contravariant=False, infer_variance=False, default=NoDefault)
See
typing.TypeVar.The
typing_extensionsversion adds support for thedefault=argument from PEP 696, as well as theinfer_variance=argument from PEP 695 (also available in Python 3.12).Added in version 4.4.0: Added in order to support the new
default=andinfer_variance=arguments.Changed in version 4.6.0: The implementation was changed for compatibility with Python 3.12.
Changed in version 4.12.0: The
__default__attribute is now set toNoneifdefault=Noneis passed, and toNoDefaultif no value is passed.Previously, passing
Nonewould result in__default__being set totypes.NoneType, and passing no value for the parameter would result in__default__being set toNone.Changed in version 4.12.0: TypeVars now have a
has_default()method, for compatibility withtyping.TypeVaron Python 3.13+.
- class TypeVarTuple(name, *, default=NoDefault)¶
See
typing.TypeVarTupleand PEP 646. Intypingsince 3.11.The
typing_extensionsversion adds support for thedefault=argument from PEP 696.Added 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.
Changed in version 4.12.0: The
__default__attribute is now set toNoneifdefault=Noneis passed, and toNoDefaultif no value is passed.Previously, passing
Nonewould result in__default__being set totypes.NoneType, and passing no value for the parameter would result in__default__being set toNone.Changed in version 4.12.0: TypeVarTuples now have a
has_default()method, for compatibility withtyping.TypeVarTupleon Python 3.13+.Changed in version 4.12.0: It is now disallowed to use a TypeVar with a default value after a TypeVarTuple in a type parameter list. This matches the CPython implementation of PEP 696 on Python 3.13+.
- Unpack¶
See
typing.Unpackand PEP 646. Intypingsince 3.11.In Python 3.12, the
repr()was changed as a result of PEP 692.typing_extensionsbackports this change.Generic type aliases involving
Unpackmay not work correctly on Python 3.10 and lower; see issue #103 for details.Added 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.Added in version 4.6.0.
Protocols¶
- class SupportsAbs¶
See
typing.SupportsAbs.typing_extensionsbackports a more performant version of this protocol on Python 3.11 and lower.Added in version 4.6.0.
- class SupportsBytes¶
See
typing.SupportsBytes.typing_extensionsbackports a more performant version of this protocol on Python 3.11 and lower.Added in version 4.6.0.
- class SupportsComplex¶
-
typing_extensionsbackports a more performant version of this protocol on Python 3.11 and lower.Added in version 4.6.0.
- class SupportsFloat¶
See
typing.SupportsFloat.typing_extensionsbackports a more performant version of this protocol on Python 3.11 and lower.Added in version 4.6.0.
- class SupportsIndex¶
See
typing.SupportsIndex. Intypingsince 3.8.typing_extensionsbackports 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_extensionsbackports a more performant version of this protocol on Python 3.11 and lower.Added in version 4.6.0.
- class SupportsRound¶
See
typing.SupportsRound.typing_extensionsbackports a more performant version of this protocol on Python 3.11 and lower.Added 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. Intypingsince 3.11.Python 3.12 adds the
frozen_defaultparameter;typing_extensionsbackports this parameter.Added in version 4.1.0.
Changed in version 4.2.0: The
field_descriptorsparameter was renamed tofield_specifiers. For compatibility, the decorator now accepts arbitrary keyword arguments.Changed in version 4.5.0: The
frozen_defaultparameter was added.
- @deprecated(msg, *, category=DeprecationWarning, stacklevel=1)¶
See
warnings.deprecated()and PEP 702. In thewarningsmodule since Python 3.13.Added in version 4.5.0.
Changed in version 4.9.0: Inheriting from a deprecated class now also raises a runtime
DeprecationWarning.
- @disjoint_base¶
See PEP 800. A class decorator that marks a class as a “disjoint base”, meaning that child classes of the decorated class cannot inherit from other disjoint bases that are not parent classes of the decorated class.
This helps type checkers to detect unreachable code and to understand when two types can overlap.
Added in version 4.15.0.
- @final¶
See
typing.final()and PEP 591. Intypingsince 3.8.Since Python 3.11, this decorator supports runtime introspection by setting the
__final__attribute wherever possible;typing_extensions.finalbackports 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.overloadbackports this feature.Changed in version 4.2.0: Introspection support via
get_overloads()was added.
- @override¶
See
typing.override()and PEP 698. Intypingsince 3.12.Added 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(). Intypingsince 3.8.In Python 3.12, the performance of runtime-checkable protocols was improved, and
typing_extensionsbackports these performance improvements.
Functions¶
- assert_never(arg)¶
See
typing.assert_never(). Intypingsince 3.11.Added in version 4.1.0.
- assert_type(val, typ)¶
See
typing.assert_type(). Intypingsince 3.11.Added in version 4.2.0.
- clear_overloads()¶
See
typing.clear_overloads(). Intypingsince 3.11.Added in version 4.2.0.
- evaluate_forward_ref(forward_ref, *, owner=None, globals=None, locals=None, type_params=None, format=None)¶
Evaluate an
typing.ForwardRefas a type hint.This is similar to calling
annotationlib.ForwardRef.evaluate(), but unlike that method,evaluate_forward_ref()also:Recursively evaluates forward references nested within the type hint. However, the amount of recursion is limited in Python 3.8 and 3.10.
Raises
TypeErrorwhen it encounters certain objects that are not valid type hints.Replaces type hints that evaluate to
Nonewithtypes.NoneType.Supports the
Format.FORWARDREFandFormat.STRINGformats.
forward_ref must be an instance of
typing.ForwardRef. owner, if given, should be the object that holds the annotations that the forward reference derived from, such as a module, class object, or function. It is used to infer the namespaces to use for looking up names. globals and locals can also be explicitly given to provide the global and local namespaces. type_params is a tuple of type parameters that are in scope when evaluating the forward reference. This parameter must be provided (though it may be an empty tuple) if owner is not given and the forward reference does not already have an owner set. format specifies the format of the annotation and is a member of theFormatenum, defaulting toFormat.VALUE.Added in version 4.13.0.
- get_annotations(obj, *, globals=None, locals=None, eval_str=False, format=Format.VALUE)¶
See
inspect.get_annotations(). In the standard library since Python 3.10.typing_extensionsadds the keyword argumentformat, as specified by PEP 649. The supported formats are listed in theFormatenum. The default format,Format.VALUE, behaves the same across all versions. For the other two formats,typing_extensionsprovides a rough approximation of the PEP 649 behavior on versions of Python that do not support it.The purpose of this backport is to allow users who would like to use
Format.FORWARDREForFormat.STRINGsemantics once PEP 649 is implemented, but who also want to support earlier Python versions, to simply write:typing_extensions.get_annotations(obj, format=Format.FORWARDREF)
Added in version 4.13.0.
- get_args(tp)¶
See
typing.get_args(). Intypingsince 3.8.This function was changed in 3.9 and 3.10 to deal with
AnnotatedandParamSpeccorrectly;typing_extensionsbackports these fixes.
- get_origin(tp)¶
See
typing.get_origin(). Intypingsince 3.8.This function was changed in 3.9 and 3.10 to deal with
AnnotatedandParamSpeccorrectly;typing_extensionsbackports 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 someNamedTupleorTypedDictclasses on Python <=3.11.Added in version 4.6.0.
- get_overloads(func)¶
See
typing.get_overloads(). Intypingsince 3.11.Before Python 3.11, this works only with overloads created through
overload(), not withtyping.overload().Added in version 4.2.0.
- get_protocol_members(tp)¶
See
typing.get_protocol_members(). Intypingsince 3.13.Return the set of members defined in a
Protocol. This works with protocols defined using eithertyping.Protocolortyping_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
TypeErrorfor arguments that are not Protocols.Added in version 4.7.0.
- get_type_hints(obj, globalns=None, localns=None, include_extras=False)¶
-
In Python 3.11, this function was changed to support the new
typing.Requiredandtyping.NotRequired.typing_extensionsbackports these fixes.Changed in version 4.1.0: Interaction with
RequiredandNotRequired.Changed in version 4.11.0: When
include_extra=False,get_type_hints()now stripsReadOnlyfrom the annotation.
- is_protocol(tp)¶
See
typing.is_protocol(). Intypingsince 3.13.Determine if a type is a
Protocol. This works with protocols defined using eithertyping.Protocolortyping_extensions.Protocol.For example:
class P(Protocol): def a(self) -> str: ... b: int is_protocol(P) # => True is_protocol(int) # => False
Added in version 4.7.0.
- is_typeddict(tp)¶
See
typing.is_typeddict(). Intypingsince 3.10.On versions where
TypedDictis not the same astyping.TypedDict, this function recognizesTypedDictclasses created through either mechanism.Added in version 4.1.0.
Changed in version 4.7.0:
is_typeddict()now returnsFalsewhen called withTypedDictitself as the argument, consistent with the behavior oftyping.is_typeddict().
- reveal_type(obj)¶
See
typing.reveal_type(). Intypingsince 3.11.Added in version 4.1.0.
- type_repr(value)¶
See
annotationlib.type_repr(). Inannotationlibsince 3.14.Convert an arbitrary Python value to a format suitable for use by the
Format.STRING.Added in version 4.15.0.
Enums¶
- class Format¶
The formats for evaluating annotations introduced by PEP 649. Members of this enum can be passed as the format argument to
get_annotations().The final place of this enum in the standard library has not yet been determined (see PEP 649 and PEP 749), but the names and integer values are stable and will continue to work.
- VALUE¶
Equal to 1. The default value. The function will return the conventional Python values for the annotations. This format is identical to the return value for the function under earlier versions of Python.
- VALUE_WITH_FAKE_GLOBALS¶
Equal to 2. Special value used to signal that an annotate function is being evaluated in a special environment with fake globals. When passed this value, annotate functions should either return the same value as for the
Format.VALUEformat, or raiseNotImplementedErrorto signal that they do not support execution in this environment. This format is only used internally and should not be passed to the functions in this module.
- FORWARDREF¶
Equal to 3. When PEP 649 is implemented, this format will attempt to return the conventional Python values for the annotations. However, if it encounters an undefined name, it dynamically creates a proxy object (a ForwardRef) that substitutes for that value in the expression.
typing_extensionsemulates this value on versions of Python which do not support PEP 649 by returning the same value as forVALUEsemantics.
- STRING¶
Equal to 4. When PEP 649 is implemented, this format will produce an annotation dictionary where the values have been replaced by strings containing an approximation of the original source code for the annotation expressions.
typing_extensionsemulates this by evaluating the annotations usingVALUEsemantics and then stringifying the results.
Added in version 4.13.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: ...
Added in version 4.8.0: See PEP 727.
Capsule objects¶
- class CapsuleType¶
The type of capsule objects. See
types.CapsuleType, where it has existed since Python 3.13.Note that this may not exist on all implementations of Python; it is only guaranteed to exist on CPython.
Added in version 4.12.0.
Sentinel objects¶
- class Sentinel(name, repr=None)¶
A type used to define sentinel values. The name argument should be the name of the variable to which the return value shall be assigned.
If repr is provided, it will be used for the
__repr__()of the sentinel object. If not provided,"<name>"will be used.Example:
>>> from typing_extensions import Sentinel, assert_type >>> MISSING = Sentinel('MISSING') >>> def func(arg: int | MISSING = MISSING) -> None: ... if arg is MISSING: ... assert_type(arg, MISSING) ... else: ... assert_type(arg, int) ... >>> func(MISSING)
Added in version 4.14.0: See PEP 661
Pure aliases¶
Most of these are simply re-exported from the typing module on all supported
versions of Python, but all are listed here for completeness.
- class AbstractSet¶
See
typing.AbstractSet.Added in version 4.7.0.
- AnyStr¶
See
typing.AnyStr.Added in version 4.7.0.
- class AsyncContextManager¶
See
typing.AsyncContextManager. Intypingsince 3.5.4 and 3.6.2.Changed in version 4.12.0:
AsyncContextManagernow has an optional second parameter, defaulting toOptional[bool], signifying the return type of the__aexit__method.
- class AsyncGenerator¶
See
typing.AsyncGenerator. Intypingsince 3.6.1.Changed in version 4.12.0: The second type parameter is now optional (it defaults to
None).
- class AsyncIterable¶
See
typing.AsyncIterable. Intypingsince 3.5.2.
- class AsyncIterator¶
See
typing.AsyncIterator. Intypingsince 3.5.2.
- class Awaitable¶
See
typing.Awaitable. Intypingsince 3.5.2.
- class BinaryIO¶
See
typing.BinaryIO.Added in version 4.7.0.
- Callable¶
See
typing.Callable.Added in version 4.7.0.
- class ChainMap¶
See
typing.ChainMap. Intypingsince 3.5.4 and 3.6.1.
- ClassVar¶
See
typing.ClassVarand PEP 526. Intypingsince 3.5.3.
- class Collection¶
See
typing.Collection.Added in version 4.7.0.
- class Container¶
See
typing.Container.Added in version 4.7.0.
- class ContextManager¶
See
typing.ContextManager. Intypingsince 3.5.4.Changed in version 4.12.0:
ContextManagernow has an optional second parameter, defaulting toOptional[bool], signifying the return type of the__exit__method.
- class Coroutine¶
See
typing.Coroutine. Intypingsince 3.5.3.
- class Counter¶
See
typing.Counter. Intypingsince 3.5.4 and 3.6.1.
- class DefaultDict¶
See
typing.DefaultDict. Intypingsince 3.5.2.
- class Deque¶
See
typing.Deque. Intypingsince 3.5.4 and 3.6.1.
- class Dict¶
See
typing.Dict.Added in version 4.7.0.
- class ForwardRef¶
See
typing.ForwardRef.Added in version 4.7.0.
- class FrozenSet¶
See
typing.FrozenSet.Added in version 4.7.0.
- class Generator¶
See
typing.Generator.Added in version 4.7.0.
Changed in version 4.12.0: The second type and third type parameters are now optional (they both default to
None).
- class Generic¶
See
typing.Generic.Added in version 4.7.0.
- class Hashable¶
See
typing.Hashable.Added in version 4.7.0.
- class ItemsView¶
See
typing.ItemsView.Added in version 4.7.0.
- class Iterable¶
See
typing.Iterable.Added in version 4.7.0.
- class Iterator¶
See
typing.Iterator.Added in version 4.7.0.
- class KeysView¶
See
typing.KeysView.Added in version 4.7.0.
- class List¶
See
typing.List.Added in version 4.7.0.
- class Mapping¶
See
typing.Mapping.Added in version 4.7.0.
- class MappingView¶
See
typing.MappingView.Added in version 4.7.0.
- class Match¶
See
typing.Match.Added in version 4.7.0.
- class MutableMapping¶
-
Added in version 4.7.0.
- class MutableSequence¶
-
Added in version 4.7.0.
- class MutableSet¶
See
typing.MutableSet.Added in version 4.7.0.
- NoReturn¶
See
typing.NoReturn. Intypingsince 3.5.4 and 3.6.2.
- Optional¶
See
typing.Optional.Added in version 4.7.0.
- class OrderedDict¶
See
typing.OrderedDict. Intypingsince 3.7.2.
- class Pattern¶
See
typing.Pattern.Added in version 4.7.0.
- class Reversible¶
See
typing.Reversible.Added in version 4.7.0.
- class Sequence¶
See
typing.Sequence.Added in version 4.7.0.
- class Set¶
See
typing.Set.Added in version 4.7.0.
- class Sized¶
See
typing.Sized.Added in version 4.7.0.
- class Text¶
See
typing.Text. Intypingsince 3.5.2.
- class TextIO¶
See
typing.TextIO.Added in version 4.7.0.
- Tuple¶
See
typing.Tuple.Added in version 4.7.0.
- class Type¶
See
typing.Type. Intypingsince 3.5.2.
- TYPE_CHECKING¶
See
typing.TYPE_CHECKING. Intypingsince 3.5.2.
- Union¶
See
typing.Union.Added in version 4.7.0.
- class ValuesView¶
See
typing.ValuesView.Added in version 4.7.0.
- cast()¶
See
typing.cast().Added in version 4.7.0.
- @no_type_check¶
-
Added in version 4.7.0.
- @no_type_check_decorator¶
See
typing.no_type_check_decorator().Added in version 4.7.0.
Security¶
typing_extensions is among the most widely used packages in the
Python ecosystem. Therefore, we take security seriously and strive
to use a transparent, secure release process.
We commit to the following in order to keep the package secure in the future:
typing_extensionswill never include any native extensions, only pure Python code.typing_extensionswill not have any third-party dependencies.We will follow best practices for a secure release process.
If you have any feedback on our security process, please open an issue. To report an issue privately, use GitHub’s private reporting feature.