Python | 类型检查
1. 简介
为什么需要参数类型检测
def add(a: int, b: int) -> int:
return a + b
if __name__ == '__main__':
print(add(1, 2))
print(add('Name: ', 'yimt'))
2. 示例
2.1. 代码结构
hello-python
├── main.py
└── type_check.py
2.2. 代码
type_check.py
from typing import get_type_hints
from functools import wraps
from inspect import getfullargspec
def validate_input(obj, **kwargs):
hints = get_type_hints(obj)
for param_name, param_type in hints.items():
if param_name == 'return':
continue
if not isinstance(kwargs[param_name], param_type) and not issubclass(type(kwargs[param_name]), param_type):
raise TypeError(f'参数: {param_name} 应该是: {param_type}或子类')
def type_check(decorator):
@wraps(decorator)
def wrapped_decorator(*args, **kwargs):
func_args = getfullargspec(decorator)[0]
kwargs.update(dict(zip(func_args, args)))
validate_input(decorator, **kwargs)
return decorator(**kwargs)
return wrapped_decorator
main.py
from type_check import type_check
@type_check
def add(a: int, b: int) -> int:
return a + b
class A:
def __init__(self, value: int):
self.value = value
class B(A):
def __init__(self, value: int):
super().__init__(value)
@type_check
def add_obj(a: A, b: A) -> int:
return a.value + b.value
if __name__ == '__main__':
print(add(1, 2))
print(add_obj(A(1), B(2)))
print(add_obj(A(1), 2))
3. 总结
什么情况下该验证参数?
Python中类型检查是运行时,如果大量的类型检查会有一定的性能消耗。正常我们开发都是以模块为单位,我们只在暴露给外部其他模块调用的方法做类型检查,自身内部的调用不做类型检查。
4. 参考
|