Home > Mobile >  Call a function without calling function's wrapper function
Call a function without calling function's wrapper function

Time:07-29

Let's say I have a function:

@some_authorization
def to_call():
  pass

Now, I want to call this to_call() function, but don't want that wrapper function @some_authorization get executed. How to achieve this scenario?

CodePudding user response:

When you decorate a function, you are reassigning its name to whatever is returned by the decorator. If you don't want that, do not decorate the method.

Instead, you can call the decorator as a standard function, passing to it the function, and assign the result to a different name.

def some_authorization(f):
    def func(*args, **kwargs):
        print("authorizing")
        return f(*args, **kwargs)
    return func



def to_call():
    pass

authorized_to_call = some_authorization(to_call)

print('to call')
to_call()
print('authorized to call')
authorized_to_call()

(some_authorization is the exact same decorator you would use to decorate to_call otherwise)

CodePudding user response:

To add to @matszwecja's answer, a decorator need not necessarily return a function (in fact, it need not return anything callable at all, but that'd be a bad idea). So you could return an object that is callable but also allows one to retrieve the original function:

def keeping_original_fun(decorator):
    class WrappedFun:
        def __init__(self, fun):
            self.fun = fun
            self.decorated_fun = decorator(fun)
        def __call__(self, *args, **kwargs):
            return self.decorated_fun(*args, **kwargs)
    return WrappedFun

So instead of decorating with some_authorization, you could do

@keeping_original_fun(some_authorization)
def to_call():
  pass

And this way you can still access the original description of to_call through to_call.fun.

  • Related