Welcome to the Comprehensive Guide to Typeguard for Python Type Checking
Typeguard is a runtime type checker for Python that raises type errors when your code uses incorrect types. It is highly useful in catching bugs and improving code quality by enforcing type hints. In this guide, we will introduce Typeguard and provide a comprehensive explanation of its APIs through useful code snippets. We’ll also showcase an application example that integrates these APIs.
Getting Started with Typeguard
To install Typeguard, you can simply use pip:
pip install typeguard
Example Usage of Typeguard
Here is a basic example of how to use Typeguard to enforce type hints in a function:
from typeguard import typechecked
@typechecked def greet(name: str, age: int) -> str:
return f"Hello, {name}! You are {age} years old."
try:
print(greet("Alice", 30)) # Correct usage
print(greet("Bob", "thirty")) # This will raise a TypeError
except TypeError as e:
print(e)
Advanced Type Checking
Typeguard supports advanced type checking, including the verification of types within lists, dictionaries, and other complex data structures:
from typeguard import typechecked from typing import List, Dict
@typechecked def process_data(data: List[Dict[str, int]]) -> None:
for item in data:
print(item)
try:
process_data([{"key1": 1, "key2": 2}]) # Correct usage
process_data([{"key1": "one", "key2": 2}]) # This will raise a TypeError
except TypeError as e:
print(e)
Strict Type Checking with Typeguard
Typeguard can enforce strict type checking on variables and class attributes:
from typeguard import typechecked from typing import List
@typechecked class Inventory:
items: List[str]
def __init__(self):
self.items = []
def add_item(self, item: str) -> None:
self.items.append(item)
try:
inventory = Inventory()
inventory.add_item("apple") # Correct usage
inventory.add_item(123) # This will raise a TypeError
except TypeError as e:
print(e)
Decorators in Typeguard
Typeguard also supports checking types in custom decorators:
from typeguard import typechecked
def validate(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@typechecked @validate def sum_values(a: int, b: int) -> int:
return a + b
try:
print(sum_values(10, 20)) # Correct usage
print(sum_values("10", 20)) # This will raise a TypeError
except TypeError as e:
print(e)
Integrating Typeguard in an Application
Here’s a simple example of an application utilizing the previously introduced Typeguard functionalities:
from typeguard import typechecked from typing import List, Dict
@typechecked class User:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
def get_info(self) -> str:
return f"User: {self.name}, Age: {self.age}"
@typechecked class UserManager:
users: List[User] = []
def add_user(self, user: User) -> None:
self.users.append(user)
def get_users_info(self) -> List[str]:
return [user.get_info() for user in self.users]
try:
user1 = User("Alice", 25)
user2 = User("Bob", 30)
manager = UserManager()
manager.add_user(user1)
manager.add_user(user2)
print(manager.get_users_info()) # Correct usage
user3 = User("Charlie", "thirty") # This will raise a TypeError
manager.add_user(user3)
except TypeError as e:
print(e)
In this example, Typeguard ensures that all user data adheres to the specified types, thereby improving code reliability and maintainability.
Hash: a8ab072958aef9de6e8a2d6abbc07b6e1077a4f3e4579b10bad7eb6431834c33