Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a variable in a decorator to function's argument in a decorated function?

I am in progress to learn Python. Hopefully someone points me to correct way.
This is what I'd like to do below:

def decorate(function):     def wrap_function(*args, **kwargs):         str = 'Hello!'  # This is what I want         return function(*args, **kwargs)     return wrap_function  @decorate def print_message():     # I'd like to pass 'str' as mentioned above     # to any functions' argument like below:     print(str)  # 'str' is same as above 

Any idea? Thanks in advance.

like image 371
Japboy Avatar asked Dec 27 '09 09:12

Japboy


People also ask

How do you pass arguments in decorator functions in Python?

To fix this, you need to change the repeat decorator so that it accepts an argument that specifies the number of times a function should execute like this: @repeat(5) def say(message): ... To define the repeat decorator, the repeat(5) should return the original decorator. The new repeat function returns a decorator.

Can decorators have arguments?

The decorator arguments are accessible to the inner decorator through a closure, exactly like how the wrapped() inner function can access f . And since closures extend to all the levels of inner functions, arg is also accessible from within wrapped() if necessary.

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.


1 Answers

You can't pass it as its own name, but you can add it to the keywords.

def decorate(function):     def wrap_function(*args, **kwargs):         kwargs['str'] = 'Hello!'         return function(*args, **kwargs)     return wrap_function  @decorate def print_message(*args, **kwargs):     print(kwargs['str']) 

Alternatively you can name its own argument:

def decorate(function):     def wrap_function(*args, **kwargs):         str = 'Hello!'         return function(str, *args, **kwargs)     return wrap_function  @decorate def print_message(str, *args, **kwargs):     print(str) 

Class method:

def decorate(function):     def wrap_function(*args, **kwargs):         str = 'Hello!'         args.insert(1, str)         return function(*args, **kwargs)     return wrap_function  class Printer:     @decorate     def print_message(self, str, *args, **kwargs):         print(str) 
like image 105
Tor Valamo Avatar answered Sep 27 '22 18:09

Tor Valamo