python-@beartype

@beartype 是 Python 里的一个 函数/方法/类的装饰器,来自 beartype 库,用于 运行时类型检查。

🔹 简单解释

在 Python 里我们通常用 类型注解(type hints),例如:

1
2
3
def add(x: int, y: int) -> int:
return x + y

Python 本身不会强制检查类型(add(“a”, “b”) 也能跑)。
beartype 就是一个运行时检查工具,可以让这些类型注解 真正生效,在调用时验证输入输出是否符合注解。

1
2
3
4
5
6
7
8
9
from beartype import beartype

@beartype
def concat(a: str, b: str) -> str:
return a + b

print(concat("hello", "world")) # ✅ 正常
print(concat("hello", 123)) # ❌ TypeError

支持的功能

✅ 检查函数参数和返回值的类型

✅ 支持 List[int], Tuple[str, int], Optional[float] 等复杂注解

✅ 支持类和方法

✅ 出错时会给出清晰的报错信息