-3
# This version only accepts one argument
# def shout(fn):
#     def wrapper(name):
#         return fn(name).upper()
#     return wrapper

# This version works with any number of args
def shout(fn):
    def wrapper(*args, **kwargs):
        return fn(*args, **kwargs).upper()
    return wrapper

@shout
def greet(name):
    return f"Hi, I'm {name}."

@shout
def order(main, side):
    return f"Hi, I'd like the {main}, with a side of {side}, please."

@shout
def lol():
    return "lol"

print(greet("todd"))
print(order(side="burger", main="fries"))
print(lol())

In the above code,

def wrapper(*args, **kwargs):

print(f"abc is {fn.__name__}")

    return fn(*args, **kwargs).upper()

    return wrapper

When wrapper functions executed, how does it knows the value of arguments which are to be assigned to , * args and **kwargs. We have not defined the values of arguments here, but instead func is given the parameters.

side="burger", main="fries".

**kwargs open up the dictionary but when did we defined such dictionary?

How does side="burger", main="fries" are set as arguments of wrapper function and Why are they being assigned to args and kwargs ? Why are arguments given to fync being assigned to parameters of wrapper function?

quamrana
  • 37,849
  • 12
  • 53
  • 71
v7676
  • 31
  • 2

2 Answers2

0

They are set when you call the function. When you call the wrapper, all positional arguments are packed together into args and all keyword arguments are put into kwargs, which are then unpacked and passed to the wrapped function.

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
0

When you call:

order(side="burger", main="fries")

You are actually calling wrapper() with those parameters.

This is the time at which **kwargs is assigned.

wrapper() then goes on to call your actual function order() with *args and **kwargs.

quamrana
  • 37,849
  • 12
  • 53
  • 71
  • Why the wrapper function is called with those parameters? – v7676 Sep 19 '20 at 13:53
  • Because `@shout; def order(...)` means: `order = shout(order)` which means that now `order` refers to `wrapper` which is returned from `shout()`. – quamrana Sep 19 '20 at 14:02
  • I mean why order(side="burger", main="fries") these are being assigned to kwargs?I mean we have not written wrapper(side="burger", main="fries") ?? – v7676 Sep 19 '20 at 14:04
  • Yes, you *have* written `wrapper(side="burger", main="fries")`, because you have `@shout; def order(...)` as I said in my previous comment. – quamrana Sep 19 '20 at 14:08