API reference
Type checking
- typeguard.check_argument_types()
Check that the argument values match the annotated types.
Unless both
argsandkwargsare provided, the information will be retrieved from the previous stack frame (ie. from the function that called this).- Return type:
Literal[True]- Returns:
True- Raises:
TypeCheckError – if there is an argument type mismatch
Changed in version 4.5.0: This function was restored since its removal in v3.0.0.
- typeguard.check_return_type(retval)
Check that the return value is compatible with the return value annotation in the function.
- Parameters:
retval (
TypeVar(T)) – the value about to be returned from the call- Return type:
TypeVar(T)- Returns:
retvalunchanged- Raises:
TypeCheckError – if there is a type mismatch
Changed in version 4.5.0: This function was restored since its removal in v3.0.0.
- typeguard.check_type(value, expected_type, *, forward_ref_policy=ForwardRefPolicy.WARN, typecheck_fail_callback=None, collection_check_strategy=CollectionCheckStrategy.FIRST_ITEM)
Ensure that
valuematchesexpected_type.The types from the
typingmodule do not supportisinstance()orissubclass()so a number of type specific checks are required. This function knows which checker to call for which type.This function wraps
check_type_internal()in the following ways:Respects type checking suppression (
suppress_type_checks())Forms a
TypeCheckMemofrom the current stack frameCalls the configured type check fail callback if the check fails
Note that this function is independent of the globally shared configuration in
typeguard.config. This means that usage within libraries is safe from being affected configuration changes made by other libraries or by the integrating application. Instead, configuration options have the same default values as their corresponding fields inTypeCheckConfiguration.- Parameters:
value (
object) – value to be checked againstexpected_typeexpected_type (
Any) – a class or generic type instance, or a tuple of such thingsforward_ref_policy (
ForwardRefPolicy) – seeTypeCheckConfiguration.forward_ref_policytypecheck_fail_callback (
Optional[typeguard.TypeCheckFailCallback]) – see :attr`TypeCheckConfiguration.typecheck_fail_callback`collection_check_strategy (
CollectionCheckStrategy) – seeTypeCheckConfiguration.collection_check_strategy
- Return type:
- Returns:
value, unmodified- Raises:
TypeCheckError – if there is a type mismatch
- @typeguard.typechecked(target=None, *, forward_ref_policy=<unset>, typecheck_fail_callback=<unset>, collection_check_strategy=<unset>, debug_instrumentation=<unset>)
Instrument the target function to perform run-time type checking.
This decorator recompiles the target function, injecting code to type check arguments, return values, yield values (excluding
yield from) and assignments to annotated local variables.This can also be used as a class decorator. This will instrument all type annotated methods, including
@classmethod,@staticmethod, and@propertydecorated methods in the class.Note
When Python is run in optimized mode (
-Oor-OO, this decorator is a no-op). This is a feature meant for selectively introducing type checking into a code base where the checks aren’t meant to be run in production.- Parameters:
target (
Optional[TypeVar(T_CallableOrType, bound=Callable[...,Any])]) – the function or class to enable type checking forforward_ref_policy (
ForwardRefPolicy|Unset) – override forTypeCheckConfiguration.forward_ref_policytypecheck_fail_callback (
Union[typeguard.TypeCheckFailCallback,Unset]) – override forTypeCheckConfiguration.typecheck_fail_callbackcollection_check_strategy (
CollectionCheckStrategy|Unset) – override forTypeCheckConfiguration.collection_check_strategydebug_instrumentation (
bool|Unset) – override forTypeCheckConfiguration.debug_instrumentation
- Return type:
Import hook
- typeguard.install_import_hook(packages=None, *, cls=<class 'typeguard.TypeguardFinder'>)
Install an import hook that instruments functions for automatic type checking.
This only affects modules loaded after this hook has been installed.
- Parameters:
packages (
Iterable[str] |None) – an iterable of package names to instrument, orNoneto instrument all packagescls (
type[TypeguardFinder]) – a custom meta path finder class
- Return type:
- Returns:
a context manager that uninstalls the hook on exit (or when you call
.uninstall())
Added in version 2.6.
- class typeguard.TypeguardFinder(packages, original_pathfinder)
Wraps another path finder and instruments the module with
@typecheckedifshould_instrument()returnsTrue.Should not be used directly, but rather via
install_import_hook().Added in version 2.6.
Configuration
- typeguard.config: TypeCheckConfiguration
The global configuration object.
Used by
@typecheckedandinstall_import_hook(), and notably not used bycheck_type().
- class typeguard.TypeCheckConfiguration(forward_ref_policy=ForwardRefPolicy.WARN, typecheck_fail_callback=None, collection_check_strategy=CollectionCheckStrategy.FIRST_ITEM, debug_instrumentation=False)
You can change Typeguard’s behavior with these settings.
- typecheck_fail_callback: Callable[[TypeCheckError, TypeCheckMemo], Any]
Callable that is called when type checking fails.
Default:
None(theTypeCheckErroris raised directly)
- forward_ref_policy: ForwardRefPolicy
Specifies what to do when a forward reference fails to resolve.
Default:
WARN
- collection_check_strategy: CollectionCheckStrategy
Specifies how thoroughly the contents of collections (list, dict, etc.) are type checked.
Default:
FIRST_ITEM
- class typeguard.CollectionCheckStrategy(value)
Specifies how thoroughly the contents of collections are type checked.
This has an effect on the following built-in checkers:
AbstractSetDictListMappingSetTuple[<type>, ...](arbitrarily sized tuples)
Members:
FIRST_ITEM: check only the first itemALL_ITEMS: check all items
- class typeguard.Unset
- class typeguard.ForwardRefPolicy(value)
Defines how unresolved forward references are handled.
Members:
ERROR: propagate theNameErrorwhen the forward reference lookup failsWARN: emit aTypeHintWarningif the forward reference lookup failsIGNORE: silently skip checks for unresolveable forward references
- typeguard.warn_on_error(exc, memo)
Emit a warning on a type mismatch.
This is intended to be used as an error handler in
TypeCheckConfiguration.typecheck_fail_callback.- Return type:
Custom checkers
- typeguard.check_type_internal(value, annotation, memo)
Check that the given object is compatible with the given type annotation.
This function should only be used by type checker callables. Applications should use
check_type()instead.- Parameters:
value (
Any) – the value to checkannotation (
Any) – the type annotation to check againstmemo (
TypeCheckMemo) – a memo object containing configuration and information necessary for looking up forward references
- Return type:
- typeguard.load_plugins()
Load all type checker lookup functions from entry points.
All entry points from the
typeguard.checker_lookupgroup are loaded, and the returned lookup functions are added totypeguard.checker_lookup_functions.Note
This function is called implicitly on import, unless the
TYPEGUARD_DISABLE_PLUGIN_AUTOLOADenvironment variable is present.- Return type:
- typeguard.checker_lookup_functions: list[Callable[[Any, Tuple[Any, ...], Tuple[Any, ...]], Callable[[Any, Any, Tuple[Any, ...], TypeCheckMemo], Any] | None]]
A list of callables that are used to look up a checker callable for an annotation.
- class typeguard.TypeCheckMemo(globals, locals, *, self_type=None, config=TypeCheckConfiguration(forward_ref_policy=<ForwardRefPolicy.WARN: 2>, typecheck_fail_callback=None, collection_check_strategy=<CollectionCheckStrategy.FIRST_ITEM: 1>, debug_instrumentation=False))
Contains information necessary for type checkers to do their work.
- self_type: type | None
When running type checks within an instance method or class method, this is the class object that the first argument (usually named
selforcls) refers to.
- config: TypeCheckConfiguration
Contains the configuration for a particular set of type checking operations.
Type check suppression
- @typeguard.typeguard_ignore
Decorator to indicate that annotations are not type hints.
The argument must be a class or function; if it is a class, it applies recursively to all methods and classes defined in that class (but not to methods defined in its superclasses or subclasses).
This mutates the function(s) or class(es) in place.
- typeguard.suppress_type_checks(func=None)
Temporarily suppress all type checking.
This function has two operating modes, based on how it’s used:
as a context manager (
with suppress_type_checks(): ...)as a decorator (
@suppress_type_checks)
When used as a context manager,
check_type()and any automatically instrumented functions skip the actual type checking. These context managers can be nested.When used as a decorator, all type checking is suppressed while the function is running.
Type checking will resume once no more context managers are active and no decorated functions are running.
Both operating modes are thread-safe.
- Return type:
Union[Callable[[ParamSpec(P)],TypeVar(T)],ContextManager[None]]
Exceptions and warnings
- exception typeguard.InstrumentationWarning(message)
Emitted when there’s a problem with instrumenting a function for type checks.
- exception typeguard.TypeCheckError(message)
Raised by typeguard’s type checkers when a type mismatch is detected.
- exception typeguard.TypeCheckWarning(message)
Emitted by typeguard’s type checkers when a type mismatch is detected.
- exception typeguard.TypeHintWarning
A warning that is emitted when a type hint in string form could not be resolved to an actual type.