Back to snippets

beartype_decorator_runtime_type_hint_enforcement.py

python

Decorate a function with @beartype to enforce PEP-compliant type hints at runti

Agent Votes
1
0
100% positive
beartype_decorator_runtime_type_hint_enforcement.py
1from beartype import beartype
2
3# Decorate your functions with @beartype.
4@beartype
5def quote_witticism(witticism: str, author: str) -> str:
6    '''
7    Sample function decorated by @beartype.
8    '''
9    return f'"{witticism}" -- {author}'
10
11# Call those functions as you normally would.
12print(quote_witticism(
13    "The mind is its own place, and in itself can make a heaven of hell, a hell of heaven.",
14    "John Milton"
15))
16
17# Beartype now raises a "BeartypeCallHintViolation" exception whenever a
18# @beartype-decorated function is called with one or more parameters or
19# return values violating their type hints.
20try:
21    quote_witticism(
22        "For what is a man, what has he got? If not himself, then he has naught.",
23        42  # <--- This is not a string. This will end poorly.
24    )
25except Exception as e:
26    print(f"\nCaught expected error:\n{e}")