Welcome to typing_extensions’s documentation! — typing_extensions 4.6.0 documentation (original) (raw)
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_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 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/pepsrepository. If the PEP is accepted, the feature will then be added to thetyping 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 totyping_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 usesSemantic 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_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() 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[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 typingin 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.
Added 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 PR #481 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.
LiteralString¶
See typing.LiteralString and PEP 675. In typing since 3.11.
Added 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.
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. 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.
Added 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.
NoDefault¶
See typing.NoDefault. In typing since 3.13.
Added in version 4.12.0.
A sentinel used when the extra_items class argument to TypedDict is not provided. In typing since 3.15.
Added in version 4.13.0.
NotRequired¶
See typing.NotRequired and PEP 655. In typing since 3.11.
Added in version 4.0.0.
class ParamSpec(name, *, default=NoDefault)¶
See typing.ParamSpec and PEP 612. In typing since 3.10.
The typing_extensions version adds support for thedefault= argument from PEP 696.
On older Python versions, typing_extensions.ParamSpec may not work correctly with introspection tools like get_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 to None ifdefault=None is passed, and to NoDefault if no value is passed.
Previously, passing None would result in __default__ being set to types.NoneType, and passing no value for the parameter would result in __default__ being set to None.
Changed in version 4.12.0: ParamSpecs now have a has_default() method, for compatibility with typing.ParamSpec on Python 3.13+.
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 andtyping_extensions.Protocol simultaneously. Previously, this led toTypeError 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. Seeissue #245 for some examples.
ReadOnly¶
See typing.ReadOnly and PEP 705. In typing since 3.13.
Indicates that a TypedDict item may not be modified.
Added in version 4.9.0.
Required¶
See typing.Required and PEP 655. In typing since 3.11.
Added in version 4.0.0.
Self¶
See typing.Self and PEP 673. In typing since 3.11.
Added 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.
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.TypeGuard and PEP 647. In typing since 3.10.
TypeIs¶
See typing.TypeIs and PEP 742. In typing since 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=)¶
See typing.TypedDict and PEP 589. In typing since 3.8, but changed and enhanced in several ways since then.typing_extensions backports various bug fixes and improvements to TypedDict.
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. Thetyping_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.TypedDictraises 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 ReadOnly qualifier introduced 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.
Added 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.
Added in version 4.9.0.
The closed and extra_items keyword arguments introduced byPEP 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 TypedDict is considered closed. This reflects the closed class argument.
Added in version 4.10.0.
The type of the extra items allowed on the TypedDict. This attribute defaults to NoExtraItems if the extra_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 DeprecationWarning is now emitted when a call-basedTypedDict 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.
Changed in version 4.13.0: PEP 728 support was updated to a newer version. Extra items are now indicated with an extra_items class argument, not a special key__extra_items__.
A value assigned to __total__ in the class body of aTypedDict will be overwritten by the total argument of theTypedDict constructor.
TypeVar(name, *constraints, bound=None, covariant=False,
contravariant=False, infer_variance=False, default=NoDefault)
See typing.TypeVar.
The typing_extensions version 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 to None ifdefault=None is passed, and to NoDefault if no value is passed.
Previously, passing None would result in __default__ being set to types.NoneType, and passing no value for the parameter would result in __default__ being set to None.
Changed in version 4.12.0: TypeVars now have a has_default() method, for compatibility with typing.TypeVar on Python 3.13+.
class TypeVarTuple(name, *, default=NoDefault)¶
See typing.TypeVarTuple and PEP 646. In typing since 3.11.
The typing_extensions version 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 to None ifdefault=None is passed, and to NoDefault if no value is passed.
Previously, passing None would result in __default__ being set to types.NoneType, and passing no value for the parameter would result in __default__ being set to None.
Changed in version 4.12.0: TypeVarTuples now have a has_default() method, for compatibility with typing.TypeVarTuple on Python 3.13+.
Changed in version 4.12.0: It is now disallowed to use a TypeVar with a default value after aTypeVarTuple in a type parameter list. This matches the CPython implementation of PEP 696 on Python 3.13+.
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.
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_extensions backports 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_extensions backports a more performant version of this protocol on Python 3.11 and lower.
Added in version 4.6.0.
class SupportsComplex¶
typing_extensions backports 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_extensions backports a more performant version of this protocol on Python 3.11 and lower.
Added 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.
Added 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.
Added in version 4.6.0.
class Reader¶
See io.Reader. Added to the standard library in Python 3.14.
Added in version 4.14.0.
class Writer¶
See io.Writer. Added to the standard library in Python 3.14.
Added in version 4.14.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_extensionsbackports this parameter.
Added 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 warnings.deprecated() and PEP 702. In the warnings module 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 runtimeDeprecationWarning.
@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. In typing since 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. In typing since 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(). 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.
Added in version 4.1.0.
assert_type(val, typ)¶
See typing.assert_type(). In typing since 3.11.
Added in version 4.2.0.
clear_overloads()¶
See typing.clear_overloads(). In typing since 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.ForwardRef as 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 TypeError when it encounters certain objects that are not valid type hints.
- Replaces type hints that evaluate to
Nonewithtypes.NoneType. - Supports the Format.FORWARDREF andFormat.STRING formats.
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 the Format enum, defaulting to Format.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_extensions adds the keyword argument format, as specified by PEP 649. The supported formats are listed in the Format enum. The default format, Format.VALUE, behaves the same across all versions. For the other two formats, typing_extensions provides 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 useFormat.FORWARDREF or Format.STRING semantics oncePEP 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(). In typing since 3.8.
This function was changed in 3.9 and 3.10 to deal with Annotatedand 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 Annotatedand 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 orTypedDict classes on Python <=3.11.
Added 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 throughoverload(), not with typing.overload().
Added in version 4.2.0.
get_protocol_members(tp)¶
See typing.get_protocol_members(). In typing since 3.13.
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.
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 newtyping.Required and typing.NotRequired.typing_extensions backports these fixes.
Changed in version 4.1.0: Interaction with Required and NotRequired.
Changed in version 4.11.0: When include_extra=False, get_type_hints() now stripsReadOnly from the annotation.
is_protocol(tp)¶
See typing.is_protocol(). In typing since 3.13.
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
Added 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 astyping.TypedDict, this function recognizesTypedDict classes created through either mechanism.
Added in version 4.1.0.
Changed in version 4.7.0: is_typeddict() now returns False when called withTypedDict itself as the argument, consistent with the behavior of typing.is_typeddict().
reveal_type(obj)¶
See typing.reveal_type(). In typing since 3.11.
Added in version 4.1.0.
type_repr(value)¶
See annotationlib.type_repr(). In annotationlib since 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.VALUE format, or raise NotImplementedErrorto 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_extensions emulates this value on versions of Python which do not support PEP 649 by returning the same value as for VALUE semantics.
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_extensions emulates this by evaluating the annotations usingVALUE semantics 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.
documentation¶
The documentation string passed to Doc.
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. In typing since 3.5.4 and 3.6.2.
Changed in version 4.12.0: AsyncContextManager now has an optional second parameter, defaulting toOptional[bool], signifying the return type of the __aexit__ method.
class AsyncGenerator¶
See typing.AsyncGenerator. In typing since 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. 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.
Added in version 4.7.0.
Callable¶
See typing.Callable.
Added 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.
Added in version 4.7.0.
class Container¶
See typing.Container.
Added in version 4.7.0.
class ContextManager¶
See typing.ContextManager. In typing since 3.5.4.
Changed in version 4.12.0: ContextManager now has an optional second parameter, defaulting toOptional[bool], signifying the return type of the __exit__ method.
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.
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 IO¶
See typing.IO.
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. In typing since 3.5.4 and 3.6.2.
Optional¶
See typing.Optional.
Added in version 4.7.0.
class OrderedDict¶
See typing.OrderedDict. In typing since 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. In typing since 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. In typing since 3.5.2.
TYPE_CHECKING¶
See typing.TYPE_CHECKING. In typing since 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.