Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 644
Dschoni Avatar asked Sep 07 '16 13:09

Dschoni


People also ask

How do you call a function with a decorator in Python?

Python class decorator It is possible to use classes as decorators. For this, we need to implement the __call__ magic function. In the example, we use a class decorator to count the calls of a regular function. We call the update_wrapper function.

Can we use decorator inside a function in Python?

Nesting means placing or storing inside the other. Therefore, Nested Decorators means applying more than one decorator inside a function. Python allows us to implement more than one decorator to a function. It makes decorators useful for reusable building blocks as it accumulates the several effects together.

What is decorative function in Python?

A decorator in Python is a function that takes another function as its argument, and returns yet another function . Decorators can be extremely useful as they allow the extension of an existing function, without any modification to the original function source code.

How do you decorate a method in Python?

To decorate a method in a class, first use the '@' symbol followed by the name of the decorator function. A decorator is simply a function that takes a function as an argument and returns yet another function. Here, when we decorate, multiply_together with integer_check, the integer function gets called.


1 Answers

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.

like image 75
turkus Avatar answered Sep 23 '22 00:09

turkus