当前位置:   article > 正文

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

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

前言

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

说明

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


test("999")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 但是我就想要类型不对就直接报错
  • 确实可以另辟蹊径,实现报错,似乎有强类型语言那味了
  • 只想淡淡的说一句装饰器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
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

开始表演

@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", '嘻嘻')  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

输出结果

在这里插入图片描述

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号