简体   繁体   中英

python decorate function call

I recently learned about decorators and wondered if it's possible to use them not in a function definition but in a function call, as some kind of general wrapper.

The reason for that is, that I want to call functions from a module through a user-defined interface that does repeatable things to a function and I don't want to implement a wrapper for every single function.

In principle I would like to have something like

def a(num):
    return num

@double
a(2)

returning 4 without the need of having access to the implementation of a . Or would in this case a global wrapper like

def mutiply(factor,function,*args,**kwargs):
    return factor*function(*args,*kwargs)

be the better choice?

There is a very good detailed section on decorators in Marty Alchin's book Pro Python from Apress.

While the new style @decorator syntax is only available to be used at function/class definition, you can use the older syntax, which does the same thing this way:

from module import myfunc

myfunc = double_decorator(myfunc)

x = myfunc(2) # returns 4

You could do something like that:

def a(num):
    return num * 1

def double(f):
    def wrapped(*args, **kwargs):
        return f(*args, **kwargs)
    return wrapped

print(double(a)(2))

It's because we can decorate functions and run functions using a decorator function explicit as in the example above. So in this one:

print(double(a)(2))

In the place of a you can put any function and in place of the 2 , args and kwargs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM