2

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))
user2003548
  • 4,287
  • 5
  • 24
  • 32

2 Answers2

6

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.

Community
  • 1
  • 1
Alexander Zhukov
  • 4,357
  • 1
  • 20
  • 31
  • This is not going to work and will raise : `TypeError: () got an unexpected keyword argument 'y'` – Ashwini Chaudhary Oct 29 '13 at 11:10
  • r takes only two arguments where as you can pass variable number of positional and keyword arguments to the argument of `func`. – ajay Oct 29 '13 at 11:25
3

Problem is that the function r can accept only one argument, you need to change its definition to accept more args:

r = lambda x, y=0, *args, **kwargs: 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))
#447
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504