1

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 provide some alternate symbol name (like orig_sum) that I could then import, I just don't know how to do that.

slacy
  • 11,397
  • 8
  • 56
  • 61

2 Answers2

4
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
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
3

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.

Reiner Gerecke
  • 11,936
  • 1
  • 49
  • 41
  • Yes, that would of course work, but it doesn't have the cleanliness of the Python decorator syntax. :) As you likely have guessed, I'm actually not summing and squaring in my code, this is just a synthetic example that illustrates the behavior I want. But, your point is valid, and maybe I shouldn't use the @decorator syntax. – slacy Feb 10 '11 at 00:48
  • late to the party, but you could: @squared def squared_sum(x, y): return sum(x,y) – Willyfrog Dec 21 '12 at 14:37