开发者

Import path for decorator-wrapped function?

开发者 https://www.devze.com 2023-02-09 20:33 出处:网络
Assuming I have a decorator and a wrapped function like this: def squared(method): def wrapper(x, y): return method(x*x, y*y)

Assuming I have a decorator and a wrapped function like this:

def squared(method):
    def wrapper(x, y):
        return method(x*x, y*y)
    return wrapper

@squared
def sum(x, y):
    return x+y

I have other code that would like to call the undecorated version of the sum function. Is there an import trick that can get me to this unwrapped method? If my code says from some.module.path import sum then, I get the wrapped version of the sum method, which is not what I want in this case. (Yes, I know I could break this out into a helper method, but that breaks some of the cleanliness of the pattern I'm going for here.)

I'm okay with adding extra "magic" to the decorator to p开发者_运维技巧rovide some alternate symbol name (like orig_sum) that I could then import, I just don't know how to do that.


def unwrap(fn):
    return fn.__wrapped__

def squared(method):
    def wrapper(x, y):
        return method(x*x, y*y)
    wrapper.__wrapped__ = method
    return wrapper

@squared
def sum(x, y):
    return x+y

sum(2,3)       ->  13
unwrap(sum)(2,3)  ->  5


What about this?

def squared(method):
    def wrapper(x, y):
        return method(x*x, y*y)
    return wrapper

def sum(x, y):
    return x+y

squared_sum = squared(sum)

It's still a decorator, but you still can import squared and sum without any magic. Not sure if that's what you meant by 'helper method', but I find this much cleaner than a sum method, which actually sums the squares of its inputs.

0

精彩评论

暂无评论...
验证码 换一张
取 消