Python | 类型检查

1. 简介

为什么需要参数类型检测

def add(a: int, b: int) -> int:
    return a + b


if __name__ == '__main__':
    print(add(1, 2))  # Output: 3
    print(add('Name: ', 'yimt'))  # Output: 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):
            # 类型不匹配 and 没有继承关系
            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)))  # 将数据更新到kwargs中
        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))  # Output: 3
    print(add_obj(A(1), B(2)))  # Output: 3
    print(add_obj(A(1), 2))  # Output: TypeError: 参数: b 应该是: <class '__main__.A'>或子类

3. 总结

什么情况下该验证参数?

Python中类型检查是运行时,如果大量的类型检查会有一定的性能消耗。正常我们开发都是以模块为单位,我们只在暴露给外部其他模块调用的方法做类型检查,自身内部的调用不做类型检查。

4. 参考

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐