PEP 647 TypeGuard

E884133

PEP 647 TypeGuard is a Python typing feature that allows developers to define user-defined type guard functions, enabling more precise type narrowing and improved static type checking.

Try in SPARQL Jump to: Statements Referenced by

Statements (47)

Predicate Object
instanceOf PEP
Python typing feature
affects type checkers behavior
backportedFor Python versions earlier than 3.10
backportLocation typing_extensions.TypeGuard
belongsTo Python type system
Python typing module NERFINISHED
category Typing PEP NERFINISHED
clarifies how user-defined predicates influence type narrowing
defines typing.TypeGuard NERFINISHED
definesConcept TypeGuard NERFINISHED
definesSyntaxElement TypeGuard[X] return annotation
designDecision TypeGuard is covariant in its type parameter NERFINISHED
TypeGuard is intended only for return types, not parameters NERFINISHED
documentationLocation https://peps.python.org/pep-0647/
exampleUse def is_str_list(val: list[object]) -> TypeGuard[list[str]]
hasAuthor Eric Traut NERFINISHED
hasName PEP 647: User-Defined Type Guards NERFINISHED
introducedIn Python 3.10 NERFINISHED
language Python NERFINISHED
moduleLocation typing.TypeGuard NERFINISHED
motivatedBy limitations of isinstance-based narrowing
need for reusable predicate functions
primaryGoal enable user-defined type guards
improve static type checking precision
support more precise type narrowing
relatedTo PEP 484 NERFINISHED
PEP 544 NERFINISHED
PEP 589 NERFINISHED
replacesPattern ad-hoc isinstance checks for complex predicates
requires TypeGuard generic parameter to be a subtype of input type
returnTypeConstraint TypeGuard must be used as function return type
runtimeEffect no direct runtime enforcement
scope static type checking only
semantics if function returns True, argument type is narrowed to TypeGuard parameter
type narrowing applies only in True branch
type narrowing is local to the guarded expression
status Accepted
targetVersion Python 3.10 NERFINISHED
usedBy Pylance NERFINISHED
Pyre NERFINISHED
Pyright NERFINISHED
mypy NERFINISHED
static type checkers
usedFor flow-sensitive type analysis
refining union types
type narrowing

Referenced by (1)

Full triples — surface form annotated when it differs from this entity's canonical label.

Python 3.10 hasTypingFeature PEP 647 TypeGuard