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?
Putting
*argsand/or**kwargsas 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:
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
argsandkwargs, that’s just a convention. It’s the*and**that do the magic.The official Python documentation has a more in-depth look.