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 hints1from typing import TypeGuard, Union2 # class Cat defines a cat with meow method3class Cat: # meow returns cat sound4 def meow(self) -> str:5 return "Meow!"6 # class Dog defines a dog with bark method7class Dog: # bark returns dog sound8 def bark(self) -> str:9 return "Woof!"10 # is_cat is a type guard function for Cat11def is_cat(animal: Union[Cat, Dog]) -> TypeGuard[Cat]: # Returns True if animal is Cat, narrows type12 return isinstance(animal, Cat)13 # is_dog is a type guard function for Dog14def is_dog(animal: Union[Cat, Dog]) -> TypeGuard[Dog]: # Returns True if animal is Dog, narrows type15 return isinstance(animal, Dog)16 # make_sound uses type guards for safe method calls17def make_sound(animal: Union[Cat, Dog]) -> str: # After is_cat check, type checker knows animal is Cat18 if is_cat(animal): # Can safely call meow() on Cat19 return animal.meow() # After is_dog check, type checker knows animal is Dog20 elif is_dog(animal): # Can safely call bark() on Dog21 return animal.bark() # Fallback for unknown types22 return "Unknown"23 # Test with Cat instance24print(make_sound(Cat()))# Test with Dog instance25print(make_sound(Dog()))Output
Meow! Woof!
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