In this lesson, you will learn how to use custom type guard functions to narrow down Union types, allowing static type checkers to understand exactly what kind of data you are handling at any given moment.
The Problem: Ambiguous Types
When you use a Union type—like int | str—your IDE and static type checker (like mypy) often don’t know which specific type is present at runtime. If you try to call a method that only exists on one of those types, the type checker will flag it as an error because it's unsure if that operation is safe.
While you could use isinstance() checks everywhere, extracting this logic into a dedicated Type Guard makes your code cleaner and more expressive.
Implementing a Type Guard
To create a type guard, you write a function that returns a boolean, but you provide a special type hint using TypeGuard from the typing module. This tells the type checker: "If this function returns True, then the input variable is definitely this specific type."
from typing import TypeGuard
def is_string_list(data: list[int | str]) -> TypeGuard[list[str]]:
# We check if every item is a string
return all(isinstance(item, str) for item in data)
def process_data(data: list[int | str]):
if is_string_list(data):
# Inside this block, 'data' is treated as list[str]
# We can safely use string methods here!
print(", ".join(data).upper())
else:
# Here, 'data' is still treated as list[int | str]
print(f"Contains numbers: {data}")
Why Use Type Guards?
By using a TypeGuard, you provide a clear contract to the static type checker. Without it, even after checking the list, the type checker might still complain because it doesn't automatically "know" that your custom logic successfully refined the type. The TypeGuard acts as a bridge, giving the type checker the "proof" it needs to allow type-specific operations. This keeps your code safe without needing Any or awkward casting.
Key Takeaway: A Type Guard uses the TypeGuard hint to teach your static type checker that a specific function call guarantees a narrower type, enabling safer and more precise code analysis.