0

I am attempting to get my head around some code and I'm struggling to actually comprehend what the code is.

The following code works:

def chicken(sauce,part):
    print(f'you want the {part} of the chicken with {sauce}')

def fish(type_,portion):
    print(f'you want a {portion} {type_} ')

def order(dish,**kwargs):
    return dish(**kwargs)


order(chicken,sauce = 'BBQ',part = 'leg')
order(fish,type_ = 'salmon',portion = 'large')

But what I do not understand is what exactly is **kwargs, I understand it accepts unlimited keyword arguments, but if I attempt to check its type it errors, but I can still pass it into another function. I understand that the ** is what allows us to intake Kwargs and that kwargs is just convention, but what exactly is the combination of the asterisk and assigned word 'kwargs', I presume it must be something as I can then use it to pass into other functions (?).

Error I refer to:

def order(dish,**kwargs):
    print(type(kwargs)) # returns dictionary as expected
    print(type(**kwargs)) #error - but what is this data type exactly ? 
    return dish(**kwargs)



order(chicken,sauce = 'BBQ',part = 'leg')

I'd appreciate if someone can explain what data type it is, and why I'm unable to check it ?

Thanks

Dan
  • 23
  • 4
  • 3
    This behavior is called ["unpacking"](https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists). The expression `**kwargs` does not have a type, because it does not represent an object - the interpreter expands it into a series of keyword arguments. – 0x5453 Jan 24 '23 at 21:34
  • `**kwargs` is simply unpacking the `dict` into keyword arguments. So basically, `type(**kwargs)` is unpacking the `dict` into `type`s keyword arguments. – Axe319 Jan 24 '23 at 21:34
  • 1
    The *parameter* `kwargs` will be assigned a `dict`. `**kwargs` in the function definition the syntax that lets the function know that the dict should contain all unconsumed keyword arguments, rather than any *one* argument. `**kwargs` in a funcion *call* uses the key-value pairs to construct multiple keyword arguments. Same syntax, two quite different meanings depending on context. – chepner Jan 24 '23 at 21:34
  • ```**``` act as a deconstructor. In your case it convert the dictionary value to key-word arguments. – Maxwell D. Dorliea Jan 24 '23 at 21:36

0 Answers0