🧠 Second Brain

Search

Search IconIcon to open search

Python `*args` and `**kwargs`

Last updated Feb 9, 2024

*args and **kwargs are special syntax in Python that allow you to pass a variable number of arguments to a function.

You would use *args and **kwargs when you don’t know how many arguments the function needs to accept at the time of writing the function. This is useful when you are writing a function that can be used in many different contexts, where the number and type of arguments may vary.

arg and kwargs are just names
Note that args is just a name. You’re not required to use the name args. You can choose any name that you prefer.

# How they work

*args allows you to pass a variable number of positional arguments to a function. The * before args indicates that all the positional arguments are collected and packed into a tuple. Here is an example:

1
2
3
4
5
def my_func(*args):
    for arg in args:
        print(arg)

my_func(1, 2, 3)

In this example, my_func() takes any number of positional arguments and prints them out. When the function is called with my_func(1, 2, 3), the output would be:

1 2 3

**kwargs allows you to pass a variable number of keyword arguments to a function. The ** before kwargs indicates that all the keyword arguments are collected and packed into a dictionary. Here is an example:

1
2
3
4
5
def my_func(**kwargs):
    for key, value in kwargs.items():
        print(key, value)

my_func(name='John', age=30, city='New York')

In this example, my_func() takes any number of keyword arguments and prints out their keys and values. When the function is called with my_func(name='John', age=30, city='New York'), the output would be:

1
2
3
name John
age 30
city New York

# Using them together

You can also use *args and **kwargs together in the same function to accept any number of positional and keyword arguments. Here is an example:

1
2
3
4
5
6
7
def my_func(*args, **kwargs):
    for arg in args:
        print(arg)
    for key, value in kwargs.items():
        print(key, value)

my_func(1, 2, 3, name='John', age=30, city='New York')

In this example, my_func() takes any number of positional and keyword arguments and prints them out. When the function is called with my_func(1, 2, 3, name='John', age=30, city='New York'), the output would be:

1
2
3
4
5
6
1
2
3
name John
age 30
city New York

# Cannot be defined implicit

No, *args and **kwargs cannot be used implicitly if they are not defined as parameters in the function signature.

If you try to pass arguments using *args or **kwargs to a function that doesn’t explicitly define them as parameters, you will get a TypeError.

# Using standard parameters

If you combine it with standard arguments, the order is important.

  1. Standard arguments
  2. *args arguments
  3. **kwargs arguments

For example, this function definition is correct:

1
2
3
# correct_function_definition.py
def my_function(a, b, *args, **kwargs):
    pass

Otherwise, you get a runtime error: ```

1
2
3
4
5
$ python wrong_function_definition.py
  File "wrong_function_definition.py", line 2
    def my_function(a, b, **kwargs, *args):
                                    ^
SyntaxError: invalid syntax

# Unpacking With the Asterisk Operators: * & **

There is much more you can do with Asterisk operators, see Python args and kwargs: Demystified – Real Python.

# Special case, using args and kwargs

However, you can still access the additional arguments using the args and kwargs variables that are available inside the function. For example:

pythonCopy code

1
2
3
4
5
6
def my_func(a, b, *args, **kwargs):
    print(a, b)
    print(args)
    print(kwargs)

my_func(1, 2, 3, name='John', age=30)

In this updated function, *args and **kwargs are defined as parameters in the function signature. When the function is called with my_func(1, 2, 3, name='John', age=30), the output would be:

pythonCopy code

1
2
3
1 2
(3,)
{'name': 'John', 'age': 30}

Here, args is a tuple containing any additional positional arguments beyond the first two, and kwargs is a dictionary containing any additional keyword arguments beyond the first two.

Positional argument order
Note again that the order of the parameters in the function signature matters. *args must come after all the positional arguments, and **kwargs must come after all the positional arguments and *args.


Origin: Tweet
References:
Created 2023-03-03