Introduction to Beartype: A Fast, Flexible, and Easy-To-Use Python Library for Type Checking
Beartype is an open-source Python library designed for type checking and data validation, helping developers ensure their code adheres to specified type hints. It aims to be fast, flexible, and intuitive to use, making the development process smoother and more efficient.
Core Features and APIs of Beartype
Let’s dive into some of the key features and APIs provided by Beartype, demonstrated with code snippets.
@beartype
The primary interface for applying type checking in Beartype is the @beartype
decorator. This decorator adds runtime type checking to functions and methods.
from beartype import beartype
@beartype
def sum_two_numbers(a: int, b: int) -> int:
return a + b
@beartype.roar.BeartypeCallHintPepReturnViolation
This exception is raised when the return value of a type-hinted callable violates its return type hint.
from beartype.roar import BeartypeCallHintPepReturnViolation
from beartype import beartype
@beartype
def return_integer() -> int:
return "This is not an integer!"
try:
return_integer()
except BeartypeCallHintPepReturnViolation as e:
print(f"Type violation: {e}")
@beartype.roar.BeartypeDecorHintPep322Violation
This exception is raised for violations related to PEP 322.
from beartype.roar import BeartypeDecorHintPep322Violation
from beartype import beartype
@beartype
def func_with_pep322(a: int) -> int:
return a
try:
func_with_pep322('string_instead_of_int')
except BeartypeDecorHintPep322Violation as e:
print(f"Type violation: {e}")
Example Application with Beartype
Here’s an example application that utilizes Beartype for type checking. This is a simple calculator application that ensures input and output types adhere to the specified function signatures.
from beartype import beartype
@beartype
def add(a: int, b: int) -> int:
return a + b
@beartype
def subtract(a: int, b: int) -> int:
return a - b
@beartype
def multiply(a: int, b: int) -> int:
return a * b
@beartype
def divide(a: int, b: int) -> float:
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
if __name__ == "__main__":
print(add(5, 3))
print(subtract(5, 3))
print(multiply(5, 3))
try:
print(divide(5, 0))
except ValueError as e:
print(e)
By integrating Beartype into your Python projects, you can benefit from consistent type checking, potentially catching bugs early in the development cycle.
Hash: bfd67c1669488a44734ae4e1db98bb35491fb3c4de6496e971dff3c6c22f02e0