Home > Enterprise >  What does args and kwds means when writing function in python like help(args, kwds)
What does args and kwds means when writing function in python like help(args, kwds)

Time:07-20

I searched the internet but could not get an definite answer. Does it means arguments and keywords?

CodePudding user response:

According to this article which is using a slightly different naming convention (kwargs instead of kwds) those are

  • args - Non-Keyword Arguments
  • kwargs - Keyword Arguments

CodePudding user response:

We use *args or **kwargs when we are not sure how many arguments will be passed to a function.

Here :

*args will pass non-keyword arguments as a tuple.

**kwargs will pass key-word arguments as a dictionary.

Note you can use any variable name in place of 'args' and 'kwargs'. eg: *myargs , **mykwargs

# To help you better visualize here is an example:
def test_func(*args,**kwargs):
   print(args)
   print(kwargs)


test_func(1,2,3,4, a=1,b=2,c=3)

# Output :
(1, 2, 3, 4)
{'a': 1, 'b': 2, 'c': 3}

CodePudding user response:

In python (and some other languages) you can have those special paramters. As stated by @Michalor args is for non-Keyword Arguments and kwargs (or keyword args) is for keyword based arguments.

Here a very good example from https://book.pythontips.com/en/latest/args_and_kwargs.html

def test_args_kwargs(arg1, arg2, arg3):
   print("arg1:", arg1)
   print("arg2:", arg2)
   print("arg3:", arg3)

#first with *args. Executing the following code in main or in IDLE:

args = ("two", 3, 5)
test_args_kwargs(*args)

will result in the following output

arg1: two
arg2: 3
arg3: 5

now with **kwargs:

Executing the following code in main or in IDLE:

kwargs = {"arg3": 3, "arg2": "two", "arg1": 5}
test_args_kwargs(**kwargs)

will result in the following output:

arg1: 5
arg2: two
arg3: 3

As you can see you can basicly call any function with *args or **kwargs which will cause a list/dict to be automaticly feed into the function by the interpreter.

*args causes a list to be feed in one after another and have to be in order for the interpreter to properly find and match the list-items with the paramters.

**kwargs instead causes a dict to be feed in by their keywords and thos can be out of order but all parameters (that have no default value) need to be in the given dict to not cause the programm to fail.

Edit*: There is no need to call your dict/list args or kwargs. You could also call the list/dict what you want but you need to call the function with single asterisk for args-handling (for example *list) or double asterisk for kwargs-handling (for example **dict)

  • Related