如何在python中与类装饰器链正确地工作?

时间:2019-07-07 16:36:40

标签: python python-3.x class decorator python-decorators

我正在学习装饰器,并且了解装饰器可以通过两种方式创建:作为函数和作为类。我在this answer的指导下上课 从pep318阅读此示例,我决定重写示例4,该示例检查属性并返回函数的值类型。因此,下面是一些代码:

from inspect import signature


def accepts(*types):
    def check_types(f):
        f_args = list(signature(f).parameters)
        assert len(types) == len(f_args)
        def inner_f(*args, **kwargs):
            for (a, t) in zip(args, types):
                assert isinstance(a, t), f"arg {a} doesn't match {t}"
            return f(*args, **kwargs)

        inner_f.__name__ = f.__name__
        return inner_f
    return check_types


def returns(rtype):
    def check_returns(f):
        def new_f(*args, **kwargs):
            result = f(*args, **kwargs)
            assert isinstance(result, rtype), f"return value {result} doesn't match {rtype}"
        new_f.__name__ = f.__name__
        return new_f
    return check_returns


class CheckTypes(object):
    def __init__(self, func, *types):
        self._func = func
        self._types = types
        f_args = list(signature(self._func).parameters)
        assert len(types) == len(f_args)

    def __call__(self, *args, **kwargs):
        for number, (a, t) in enumerate(zip(args, self._types)):
            assert isinstance(a, t), f"{number} arg {a} with type {type(a)} doesn't match {t}"        


class ExternalWrapperCheckTypes(object):
    def __init__(self, *types):
        self._types = types

    def __call__(self, func):
        return CheckTypes(func, *self._types)

class CheckReturns(object):
    def __init__(self, func, *types):
        self._func = func
        self._types = types

    def __call__(self, *args, **kwargs):
        result = self._func(*args, **kwargs)
        assert isinstance(result, self._types), f"return value {result} doesn't match {self._types}"


class ExternalWrapperCheckReturns(object):

    def __init__(self, *types):
        self._types = types

    def __call__(self, func):
        return CheckReturns(func, *self._types)


@accepts(int, (int, float))
@returns((int,))
def decorated_by_functions(arg1, arg2):
    return "Incorrect output"


@ExternalWrapperCheckTypes(int, (int, float))
@ExternalWrapperCheckReturns((int,))
def decorated_by_classes(arg1, arg2):
    return "Incorrect output"


def main():
    res1 = decorated_by_functions (42, 42.42) # AssertionError: return value s doesn't match (<class 'int'>,)
    res2 = decorated_by_classes(42, 42.42) # Ignore assertion

那么,什么问题呢? decorated_by_functions将导致断言错误,但decorated_by_classes会忽略断言。在我看来-两种方法中的重载函数__call__都存在问题,我可能会返回类的实例或其他实例,但是当我返回时,行为不会改变。

1 个答案:

答案 0 :(得分:0)

更新

实际上,我的直觉是正确的-我需要返回正确的对象,这要归功于pythontips这是我们的函数,它使用参数self._func(*args, **kwargs)进行了调用。感谢大家的关注和您的宝贵时间!

最终解决方案具有以下观点:

from inspect import signature


class CheckTypes(object):
    def __init__(self, func, *types):
        self._func = func
        self._types = types
        f_args = list(signature(self._func).parameters)
        assert len(types) == len(f_args)

    def __call__(self, *args, **kwargs):
        for number, (a, t) in enumerate(zip(args, self._types)):
            assert isinstance(a, t), f"{number} arg {a} with type {type(a)} doesn't match {t}"

        return self._func(*args, **kwargs)

class ExternalWrapperCheckTypes(object):
    def __init__(self, *types):
        self._types = types

    def __call__(self, func, *args, **kwargs):
        return CheckTypes(func, *self._types)

class CheckReturns(object):
    def __init__(self, func, *types):
        self._func = func
        self._types = types

    def __call__(self, *args, **kwargs):
        result = self._func(*args, **kwargs)
        assert isinstance(result, self._types), f"return value {result} doesn't match {self._types}"

        return self._func(*args, **kwargs)

class ExternalWrapperCheckReturns(object):
    def __init__(self, *types):
        self._types = types

    def __call__(self, func, *args, **kwargs):
        return CheckReturns(func, *self._types)


@ExternalWrapperCheckTypes(int, (int, float))
@ExternalWrapperCheckReturns((int, ))
def decorated_by_classes(arg1, arg2):
    return "Incorrect output"


def main():
    ans = decorated_by_classes(42, 42.42) # AssertionError: return value s doesn't match (<class 'int'>,)
    print(ans)