【问题标题】:Decorators in Python. How to check args typePython 中的装饰器。如何检查 args 类型
【发布时间】:2018-02-24 23:45:49
【问题描述】:
def args_typecheck(func):    
    def wrapper(type):
        def inner(*args):
            if not all(map(lambda x: isinstance(x, type), args)):
                raise TypeError
            return func(*args)
        return inner
    return wrapper

@args_typecheck(str)
def seq(*args):
    return reduce(operator.eq, args)

我尝试使用装饰器检查输入参数类型。但它不起作用。

错误:

if not all(map(lambda x: isinstance(x, type), args)): E TypeError: isinstance() arg 2 必须是类型或类型的元组

【问题讨论】:

    标签: python decorator


    【解决方案1】:

    你的装饰器函数签名被颠倒了:wrapper 应该采用原始包装函数,args_typecheck 应该采用要检查的类型:

    def args_typecheck(type):
       def wrapper(func):
          def inner(*args):
            if not all(map(lambda x: isinstance(x, type), args)):
                raise TypeError
            return func(*args)
          return inner
       return wrapper
    
    @args_typecheck(str)
    def seq(*args):
      return reduce(operator.eq, args)
    

    【讨论】:

      猜你喜欢
      • 2016-08-21
      • 2019-10-05
      • 2020-07-15
      • 2016-10-06
      • 2021-10-23
      • 2018-08-28
      • 1970-01-01
      • 2022-06-17
      • 2015-06-25
      相关资源
      最近更新 更多