Search code examples
pythonpython-3.xfunctionarguments

In the given code what is the need of **kwargs when it runs without it(only with *args) also?


def greet(fx):
  def mfx(*args, **kwargs):
    print("Good Morning")
    fx(*args, **kwargs)
    print(args)
    print(kwargs)
    print("Thanks for using this function")
  return mfx
@greet
def add(a, b):
  print(a+b)
add(1, 2)

I tried using it with both arguments and with *args only but not able to find the use of **kwargs as the program runs without any problem with *args only.


Solution

  • args and kwargs are used when you don't know the quantity of arguments that are going to be given to a function.

    when using *args in a function any number of positional arguments can be excepted by it. It receives arguments as tuple.

    when using **kwargs any number of keyword arguments can be excepted by it. It receives arguments as dict.**kwargs are useful when you want to access keyword arguments but you aren't 100% sure what they will be.

    when you pass positional arguments to **kwargs error occurs and vice versa

    And in your code you used mfx(*args,**kwargs) and you gave it 1,2(positional arguments) and they all were passed to args not kwargs. if you want to give arguments to kwargs then use (a=1,b=2) if you do this the arguments will be passed to kwargs.

    if you want to know diff between keyword and positional arguments link here

    if you want to know more about args and kwargs link here