Content · Programming · Python

Python typing.TypeGuard: Narrow Types with Custom Functions

TypeGuard allows a custom predicate to narrow its argument to a specified type when it returns True.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

TypeGuard allows a custom predicate to narrow its argument to a specified type when it returns True.

What It Does and Why It Matters


TypeGuard allows a custom predicate to narrow its argument to a specified type when it returns True. It is especially useful for validating a list of unknown values before typed processing.

Annotations guide static tools; by default they do not validate external input or change the return value at runtime.

Step-by-Step Example


Start with the complete example below. Read the inputs and predict what the final print statement will show before you run it.

from typing import TypeGuard

def are_integers(values: list[object]) -> TypeGuard[list[int]]:
    return all(isinstance(value, int) and not isinstance(value, bool) for value in values)
items: list[object] = [2, 4, 6]
if are_integers(items):
    print(sum(items))

How the Code Works


  • The imports make these standard-library tools available: typing.
  • The definition of are_integers creates reusable behavior; its body runs only when called or instantiated as appropriate.
  • The name items receives the value of [2, 4, 6]. Changing this input lets you explore a different case.
  • The print calls display the results. Compare these results with the method’s documented return type and the input used.
  • The predicate returns a runtime Boolean. The annotation tells a static checker what type it may assume within the checked branch.

Expected output:

12

For the demonstrated inputs, Python displays '12'. This result follows from the operation described above; change one input at a time to understand which rule matters.

What to Notice


Pay attention to the accepted input types, the returned value and the boundary behavior. Predict what changes if you replace the example input with an empty, zero, negative or missing value, where that value is meaningful for this operation.

If the task uses a library function, inspect its documented exceptions and return type before reusing it inside a larger function.

Where You Would Use This


This helps maintain larger projects where functions and data shapes cross module boundaries. Check the code with a static analyzer, and still validate data received from files, users or remote APIs. Annotation constructs do not normally enforce types automatically at runtime.

Practice Exercise


Implement a guard ensuring that all sequence items are integers.

Before running your edited example, write down the result you expect. Then test at least one valid boundary or deliberately invalid value, using appropriate exception handling where necessary.

Reference: official Python documentation for the complete API contract and version notes.

Common Beginner Mistakes


  • Assuming a TypeGuard magically checks values; the function body must enforce the claimed condition.
  • Assuming a type checker has checked values received dynamically from an untrusted source.

Key Takeaways


  • TypeGuard allows a custom predicate to narrow its argument to a specified type when it returns True.
  • Implement a guard ensuring that all sequence items are integers.
  • Annotations guide static tools; by default they do not validate external input or change the return value at runtime.
Share this resourceSend this page to someone who may find it useful.