API reference
Type checking
- typeguard.check_type(value, expected_type, *, forward_ref_policy=ForwardRefPolicy.WARN, typecheck_fail_callback=None, collection_check_strategy=CollectionCheckStrategy.FIRST_ITEM)
Ensure that
value
matchesexpected_type
.The types from the
typing
module 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
TypeCheckMemo
from 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 – value to be checked against
expected_type
expected_type – a class or generic type instance, or a tuple of such things
forward_ref_policy – see
TypeCheckConfiguration.forward_ref_policy
typecheck_fail_callback – see :attr`TypeCheckConfiguration.typecheck_fail_callback`
collection_check_strategy – see
TypeCheckConfiguration.collection_check_strategy
- 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@property
decorated methods in the class.Note
When Python is run in optimized mode (
-O
or-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 – the function or class to enable type checking for
forward_ref_policy – override for
TypeCheckConfiguration.forward_ref_policy
typecheck_fail_callback – override for
TypeCheckConfiguration.typecheck_fail_callback
collection_check_strategy – override for
TypeCheckConfiguration.collection_check_strategy
debug_instrumentation – override for
TypeCheckConfiguration.debug_instrumentation
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, orNone
to 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
@typechecked
ifshould_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
@typechecked
andinstall_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
(theTypeCheckError
is 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, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Specifies how thoroughly the contents of collections are type checked.
This has an effect on the following built-in checkers:
AbstractSet
Dict
List
Mapping
Set
Tuple[<type>, ...]
(arbitrarily sized tuples)
Members:
FIRST_ITEM
: check only the first itemALL_ITEMS
: check all items
- class typeguard.Unset
- class typeguard.ForwardRefPolicy(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Defines how unresolved forward references are handled.
Members:
ERROR
: propagate theNameError
when the forward reference lookup failsWARN
: emit aTypeHintWarning
if 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_lookup
group are loaded, and the returned lookup functions are added totypeguard.checker_lookup_functions
. :rtype:None
Note
This function is called implicitly on import, unless the
TYPEGUARD_DISABLE_PLUGIN_AUTOLOAD
environment variable is present.
- 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
self
orcls
) 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: :rtype:
Union
[Callable
[[ParamSpec
(P
)],TypeVar
(T
)],ContextManager
[None
]]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.
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.