**kwargs in Python

black and white computer keyboard

Kwargs in Python refer to keyword arguments. A keyword argument is an argument that has a label.

For example: greet(name="Jack").

If a function takes **kwargs as an argument, it accepts any number of keyword arguments.

For example:

def info(**kwargs):
    for name, number in kwargs.items():
        print(f'Player {name} has a number {number}')

Now you can call the function with any number of keyword arguments:

info(Ronaldo=7, Messi=10, Bale=9)

Output:

Player Ronaldo has a number 7
Player Messi has a number 10
Player Bale has a number 9

To deeper understand args and kwargs in Python, keep on reading.

Arguments in Python

Before learning what keyword arguments are, it’s worthwhile to have a look at the argument types of Python.

In Python, there are three types of arguments:

  1. Default arguments
  2. Positional arguments (regular arguments)
  3. Keyword arguments

In Python, it is possible to create functions that accept any number of positional arguments or keyword arguments.

1. Default Arguments in Python

Our main focus is not on default arguments, but let’s quickly go through them for the sake of completeness.

A default argument means a function argument has a default value. In other words, you can call the function with or without an argument (or arguments).

For example:

def greet(name="friend"):
    print("Hello", name)

greet()
greet("Jack")

Output:

Hello friend
Hello Jack

Here, the default value friend is used if the name is not specified when calling the function.

2. Positional Arguments (Args) in Python

Positional arguments are the “regular” arguments you use all the time. They need to be included in the right order in a function call.

For example, here is a function that accepts two arguments:

def greet(firstname, lastname):
    print("Hello", firstname, lastname)

Now you can call this function by providing the two arguments as positional arguments like this:

greet("Jack", "Jones")

Output:

Hello Jack Jones

The key takeaway here is that the order matters. Calling the function this way expects the first argument to be the firstname and the second one to be the lastname.

But, there’s another way to call this function. You can also provide the arguments as keyword arguments. Let’s see how this can be done.

3. Keyword Arguments (Kwargs) in Python

In the previous example, you saw how positional arguments work. If you pass a function positional arguments, it expects them to be in the right order. But you can also pass arguments as keyword arguments. In this case, the order does not matter anymore.

Let’s use the above greet() function for demonstration. To pass the firstname and lastname as keyword arguments, you need to name the arguments like this:

greet(lastname="Jones", firstname="Jack")

And as you see, now the order does not matter when doing it this way. The output of this function call is also:

Hello Jack Jones

Now you understand the different argument types of Python. Let’s then see how to create functions that accept any number of arguments in Python.

*Args in Python—Any Number of Arguments

In Python, it is possible to give any number of (positional) arguments into a function. To do this, use the asterisk * in front of the argument name.

For instance, let’s create a function that sums up any number of numbers:

def sumAny(*args):
    s = 0
    for num in args:
        s += num
    return s

Now you can call this function with any number of arguments:

print(sumAny(1, 2))
print(sumAny(1, 2, 3, 4))

Output:

3
10

Under the hood, the *args becomes a list of the given arguments. This is why it’s possible to loop it through the same way as looping any other list in Python.

**Kwargs in Python—Any Number of Keyword Arguments

In Python, it is possible to give a function any number of keyword arguments as an input. To do this, the function must accept an argument that is marked with the double-asterisk **.

For instance, let’s create a function that accepts any number of keyword arguments. This function takes in any amount of player data. The player data consists of player names and numbers. The function then prints this data into the console. To do this, the function needs to accept any number of keyword arguments. This happens by adding ** in front of the argument name:

def info(**kwargs):
    for name, number in kwargs.items():
        print(f'Player {name} has a number {number}')

Now you can call this function with any number of players:

info(Ronaldo=7, Messi=10, Bale=9)
info(Bale=9, Ronaldo=7)

Output:

Player Ronaldo has a number 7
Player Messi has a number 10
Player Bale has a number 9

Player Bale has a number 9
Player Ronaldo has a number 7

This works under the hood by converting the keyword arguments into a dictionary of key-value pairs. This makes it possible to handle the arguments like any other dictionary in Python.

Use Both Args and Kwargs in Python Functions

It is possible to make a function accept both any number of arguments and any number of keyword arguments. The Python interpreter has no problem with this, as it can determine the types of arguments on the fly.

For instance, let’s create a function that takes any number of spectator names and any amount of player data as its arguments:

def info(*args, **kwargs):
    print("Soccer Game: \n")
    for name, number in kwargs.items():
        print(f"{name} plays with number {number}")
    print("")
    for spectator in args:
        print("Welcome to watch the game", spectator)

Now you can call this function with any number of spectators and any amount of player data:

info("Jack", "Sophie", "Jon", "Matt", Ronaldo=7, Messi=10, Bale=9)

Output:

Soccer Game: 

Ronaldo plays with number 7
Messi plays with number 10
Bale plays with number 9

Welcome to watch the game Jack
Welcome to watch the game Sophie
Welcome to watch the game Jon
Welcome to watch the game Matt

Args and Kwargs in Python—It’s Just a Naming Convention

Finally, it’s important you understand there’s nothing interesting in the names args and kwargs in Python. They are not reserved keywords. You could use any other name instead.

For example, the example of adding any number of numbers together could use numbers instead of args:

def sumAny(*numbers):
    s = 0
    for num in numbers:
        s += num
    return s

And the player data example could use playerdata instead of kwargs as its argument name:

def info(**playerdata):
    for name, number in playerdata.items():
        print(f'Player {name} has a number {number}')

The only thing that matters is you use:

  • * when you want to accept any number of regular (positional) arguments.
  • ** when you want to accept any number of keyword arguments.

Conclusion

In Python, it is possible to call a function with an arbitrary number of arguments. This can be applied to regular arguments or keyword arguments.

To call a function with any number of arguments the function has to use:

  • * in front of the argument name to accept any number of regular arguments.
  • ** in front of the argument name to accept any number of keyword arguments

Here is an example of a function that accepts any number of keyword arguments:

def info(**kwargs):
    for name, number in kwargs.items():
        print(f'Player {name} has a number {number}')

# You can call this function with any amount of player data:
info(Ronaldo=7, Messi=10, Bale=9)
info(Bale=9, Ronaldo=7)

And here’s one that takes any number of regular arguments:

def sumAny(*args):
    s = 0
    for num in args:
        s += num
    return s

# You can call this function with any number of numbers
print(sumAny(1,2,3))
print(sumAny(1,2,3,4,5))

Also, feel free to change the names of the args and kwargs as you wish. They are not reserved keywords in Python.

Thanks for reading. I hope you enjoy it.

Happy coding!

Further Reading

50 Python Interview Questions with Answers

50+ Buzzwords of Web Development

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *