Python - 调用函数时检查参数的类型是否合规

110 阅读1分钟

前言

  • 阅读本文大概需要3分钟

说明

  • 在python中,即使加入了类型注解,使用注解之外的类型也是不报错
def test(uid: int):
	print(uid)


test("999")
  • 但是我就想要类型不对就直接报错
  • 确实可以另辟蹊径,实现报错,似乎有强类型语言那味了
  • 只想淡淡的说一句装饰器yyds

代码实现

import inspect


def type_check(func):
    def wrapper(*args, **kwargs):
        sig = inspect.signature(func)
        bound_args = sig.bind(*args, **kwargs)
        bound_args.apply_defaults()

        for name, value in bound_args.arguments.items():
            param = sig.parameters[name]
            expected = param.annotation
            default_value = param.default

            if default_value != inspect.Parameter.empty:
                print('有默认值 => {}实际值={}'.format(name, value))
            else:
                print('无默认值 => {}'.format(name))

            # 有注解的参数
            if expected != inspect.Parameter.empty:
                # 无默认值的参数
                if default_value == inspect.Parameter.empty:
                    if not isinstance(value, expected):
                        raise TypeError(f"参数'{name}'应该是{expected}而不是{type(value)}")
                # 有默认值的参数(值必须是注解类型或者等于默认值)
                if value != default_value and not isinstance(value, expected):
                    raise TypeError(f"参数'{name}'应该是{expected}而不是{type(value)}")

        return func(*args, **kwargs)

    return wrapper
    

开始表演

@type_check
def demo(n: int, msg: str, state: int = None):
    print('正常结束\n')


# 正常调用
demo(1, 'SUCCESS')

# 正常调用
demo(2, 'SUCCESS', 200)

# 引发异常(第3个参数只能是int类型)
demo(3, 'FAILED', '哈哈')  

# 引发异常(第1个参数只能是int类型)
demo('4', "FAILED", '嘻嘻')  

输出结果

c3.png