Search code examples
python

What do *args and **kwargs mean?


What exactly do *args and **kwargs mean?

According to the Python documentation, from what it seems, it passes in a tuple of arguments.

def foo(hello, *args):
    print(hello)

    for each in args:
        print(each)

if __name__ == '__main__':
    foo("LOVE", ["lol", "lololol"])

This prints out:

LOVE
['lol', 'lololol']

How do you effectively use them?


Solution

  • Putting *args and/or **kwargs as the last items in your function definition’s argument list allows that function to accept an arbitrary number of arguments and/or keyword arguments.

    For example, if you wanted to write a function that returned the sum of all its arguments, no matter how many you supply, you could write it like this:

    def my_sum(*args):
        return sum(args)
    

    It’s probably more commonly used in object-oriented programming, when you’re overriding a function, and want to call the original function with whatever arguments the user passes in.

    You don’t actually have to call them args and kwargs, that’s just a convention. It’s the * and ** that do the magic.

    There's a more in-depth look in the official Python documentation on arbitrary argument lists.