python *args and **kwargs explained

Share on facebook
Share on google
Share on twitter
Share on linkedin

You are entering a new codebase, the code looks good, well organized and well commented.

Then you notice a few methods with these weird *args, **kwargs


then you dive into that function and see it passes those forward to other function or handling those weird params.

So… what are those?

*args –

that is the shorthand of accessing an unknown amount of params in the function. For example, let’s create a avg function:

def avg_numbers(*args):
    return sum(args) / len(args)

res = sum_numbers(5,1,1,2,6)

So as you can see here, I can pass how many variables I want to the avg_numbers function and it will be handled properly. You can always use the normal method params with *args like this example

def first_and_others(first, *args):
    print(" ".join(args)) 

first_and_others("Im First", "the", "rest", "of", "us")

the above function will print:

the rest of us

**kwargs –
that is for accessing the keyworded params as a dictionary. Lets start with a simple example:

def first_and_second(**kwargs):

first_and_second(first="sss", sec="cxc")
As you can see here we get easy access to the passed params.
Important note, you are not forced to use *args, **kwargs as the variable names, you can use *big_list, **big_dict it’s only a convention in the python world. What you are forced to have are thos single and double *
The second note is that you can can use different variations of those two “magic” params. You can have only *args or only *kwargs or a mix with the “regular” params we all know