带参数的Python装饰器中的最大代码重用

时间:2012-08-01 16:22:28

标签: python decorator

我设法编写了一个带参数的装饰器,但是我对两个实际装饰器都有相同代码行的事实感到困扰:

def wrapper(*args, **kwargs):
    r = fn(*args)

并且想知道是否有某种方法来解决这种违反DRY的行为

def fix(double):
    def outer(fn):
        if double:
            def wrapper(*args, **kwargs):
                r = fn(*args)
                return 2 * r
            return wrapper
        else:
            def wrapper(*args, **kwargs):
                r = fn(*args)
                return r
            return wrapper
    return outer

2 个答案:

答案 0 :(得分:2)

如果double为False,您可以乘以1:

def fix(double):
    def outer(fn):
        factor = 2 if double else 1
        def wrapper(*args, **kwargs):
            r = fn(*args)
            return factor * r
        return wrapper
    return outer

答案 1 :(得分:2)

另一种选择可能是

def fix(double):
    def outer(fn):
        def wrapper(*args, **kwargs):
            r = fn(*args, **kwargs) # do that right!
            return 2 * r if double else r
        return wrapper
    return outer

或甚至 - 如果doubleFalse,则不会更改任何内容 -

def fix(double):
    def outer(fn):
        if not double: return fn
        def wrapper(*args, **kwargs):
            r = fn(*args, **kwargs) # do that right!
            return 2 * r
        return wrapper
    return outer