为何typeguard未对函数执行类型检查?
关于typeguard的@typechecked装饰器警告问题
未添加@typechecked装饰器时,函数可正常运行;添加该装饰器后,运行会弹出警告,提示未执行类型检查。
代码示例
from typeguard import typechecked @typechecked def my_func(x, y): z = x + y return z a = my_func(1, 2) print(a)
运行输出
(venv) me@ubuntu-pcs:~/PycharmProjects/project$ python3 foo/bar.py /home/me/miniconda3/envs/venv/lib/python3.9/site-packages/typeguard/__init__.py:1016: UserWarning: no type annotations present -- not typechecking __main__.my_func warn('no type annotations present -- not typechecking {}'.format(function_name(func))) 3
(注:原输出中的1 2 None应为笔误,my_func(1,2)实际返回值为3)
问题原因
@typechecked装饰器的作用是对函数的参数和返回值做类型校验,但它必须依赖函数的类型注解才能工作。如果函数没有定义任何参数或返回值的类型,装饰器无法执行检查逻辑,因此会抛出该警告。
解决方法
给函数添加明确的类型注解即可消除警告,同时让装饰器的类型校验生效:
from typeguard import typechecked @typechecked def my_func(x: int, y: int) -> int: z = x + y return z a = my_func(1, 2) print(a)
此时运行不会有警告,且如果传入不符合注解的参数(比如字符串),装饰器会直接抛出类型错误,达到校验目的。
内容的提问来源于stack exchange,提问作者DanielBell99
相关产品推荐
相关产品推荐

