Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to insert new variable in (*args,**kwargs) section?

i want to make a decoration method to assign the variable which the function would use but wouldn't be deliver by itself.

for example add new variable y in lambda r,i wrote code in this way but didn't work.

r = lambda x:x+y

def foo(func):
    def wrapped(*args,**kwargs):
        y = 3
        return func(y=y,*args,**kwargs)
    return wrapped

r = foo(r)
print(r(444))

this wouldn't work too

r = lambda x:x+y

def foo(func):
    def wrapped(*args,**kwargs):
        y = 3
        return func(*args,**kwargs)
    return wrapped

r = foo(r)
print(r(444))
like image 654
user2003548 Avatar asked Nov 25 '25 03:11

user2003548


1 Answers

kwargs is a casual python dict type, so you can just set the value of the y key to be 3

r = lambda x, y=0:x+y

def foo(func):
    def wrapped(*args,**kwargs):
        print type(kwargs) #  will output <type 'dict'>
        kwargs['y'] = 3
        return func(*args,**kwargs)
    return wrapped

In Understanding kwargs in Python this is explained in details.

like image 123
Alexander Zhukov Avatar answered Nov 26 '25 16:11

Alexander Zhukov