Type Guard Pattern in Python

Level 5508 keystrokes

This uses TypeGuard to create type narrowing functions for safer type handling in unions.

Python code

# Import TypeGuard (Python 3.10+) and Union for the type hints
1from typing import TypeGuard, Union
2
# class Cat defines a cat with meow method
3class Cat:
# meow returns cat sound
4 def meow(self) -> str:
5 return "Meow!"
6
# class Dog defines a dog with bark method
7class Dog:
# bark returns dog sound
8 def bark(self) -> str:
9 return "Woof!"
10
# is_cat is a type guard function for Cat
11def is_cat(animal: Union[Cat, Dog]) -> TypeGuard[Cat]:
# Returns True if animal is Cat, narrows type
12 return isinstance(animal, Cat)
13
# is_dog is a type guard function for Dog
14def is_dog(animal: Union[Cat, Dog]) -> TypeGuard[Dog]:
# Returns True if animal is Dog, narrows type
15 return isinstance(animal, Dog)
16
# make_sound uses type guards for safe method calls
17def make_sound(animal: Union[Cat, Dog]) -> str:
# After is_cat check, type checker knows animal is Cat
18 if is_cat(animal):
# Can safely call meow() on Cat
19 return animal.meow()
# After is_dog check, type checker knows animal is Dog
20 elif is_dog(animal):
# Can safely call bark() on Dog
21 return animal.bark()
# Fallback for unknown types
22 return "Unknown"
23
# Test with Cat instance
24print(make_sound(Cat()))
# Test with Dog instance
25print(make_sound(Dog()))

Output

Meow!
Woof!
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • (× 17
  • )× 17
  • :× 12
  • _× 7
  • ,× 6
  • "× 6
  • -× 5
  • [× 5
  • ]× 5
  • >× 5

More Python examples at level 5

← Python typing practice