+ 1

How to use decorators on functions with arguments?

def decor(func): def wrap(): print("============") func() print("============") return wrap @decor def print_text(x): print("Hello {0} !".format(x) ) print_text(72); Modify this and make it run. Thanks.

29th Nov 2016, 3:24 PM
Manpreet Singh
Manpreet Singh - avatar
5 Antworten
+ 2
def decor(func): def wrap(*args, **kwargs): print("============") func(*args, **kwargs) print("============") return wrap @decor def print_text(x): print("Hello {0} !".format(x) ) print_text(72);
29th Nov 2016, 8:40 PM
donkeyhot
donkeyhot - avatar
+ 2
You should use *args, **kwargs generally, if you want your decorator to work with all possible functions. Suppose you have to decorate a function with 2 or even unknown number of arguments, like print. https://docs.python.org/3/library/functions.html?highlight=print#print It has unknown number of arguments and several default arguments like 'sep', 'end' and so on: >>> print(1,2) 1 2 >>> print(1,2,3) 1 2 3 >>> print(1,2,3, sep='-') 1-2-3 >>> print(1,2,3, sep='-', end='!') 1-2-3! * in *args, **kwargs means unpack operation. For instance: >>> a = (1,2,3) >>> print(a) (1, 2, 3) >>> print(*a) #the same as print(1,2,3) 1 2 3 >>> d = {'sep':'-', 'end':'!'} >>> print(d) {'end': '!', 'sep': '-'} >>> print(*d) end sep >>> print(*a, **d) #the same as print(1,2,3, sep='-', end='!') 1-2-3! args is the python name for a tuple of positional argument values passed to your function, while kwargs is the dictionary of keyword argument values: >>> def decor(func): def wrap(*args, **kwargs): print('args:', args) print('kwargs:', kwargs) func(*args, **kwargs) return wrap >>> @decor def printsum(a,b,c,d=0): print(a+b+c+d) >>> printsum(1,2,c=3,d=4) args: (1, 2) kwargs: {'c': 3, 'd': 4} 10 https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/
2nd Dec 2016, 5:18 PM
donkeyhot
donkeyhot - avatar
+ 1
This also works. Can anyone explain why? How argument in print_text is carried in wrap function inside decorator? #-------------------------------------- #-------------------------------------- def decor(func): def wrap(y): print("============") func(y) print("============") return wrap @decor def print_text(x): print("Hello {0} !".format(x) ) print_text(72); #-------------------------------------- #--------------------------------------
30th Nov 2016, 6:22 AM
Manpreet Singh
Manpreet Singh - avatar
0
These *args, **kwargs. Can you explain them little bit. Are these given in the SoloLearn python? Right now i am in the Object Oriented module and i haven't seen them yet.
30th Nov 2016, 5:47 AM
Manpreet Singh
Manpreet Singh - avatar
7th Jun 2018, 1:59 AM
Denys Yeromenko
Denys Yeromenko - avatar