Python: What are *args and **kwargs?

adamlombard

Adam Lombard

Posted on January 12, 2020

Python: What are *args and **kwargs?

We may encounter Python function definitions that look something like this:

def a_function(*args, **kwargs):
    ...
Enter fullscreen mode Exit fullscreen mode

The asterisks denote parameters able to receive variable-length arguments. (The args and kwargs names don't matter — they're merely conventions, and stand for 'arguments' and 'keyword arguments' respectively. Any appropriate parameter names may be used.)

Say we need a function enabling users to share their hobbies, but we don't know in advance how many hobbies a given user will have:

def my_hobbies(*hobbies):
    print("My hobbies: " + ", ".join(hobbies))
Enter fullscreen mode Exit fullscreen mode

Our function now accepts one or more arguments:

>>> my_hobbies('reading', 'writing')
My hobbies: reading, writing

>>> my_hobbies('reading', 'writing', 'hiking', 'learning Python')
My hobbies: reading, writing, hiking, learning Python
Enter fullscreen mode Exit fullscreen mode

Conveniently, we can also call our function by passing it a tuple, using similar asterisk syntax:

>>> some_hobbies = ('reading', 'writing', 'hiking', 'learning Python')
>>> my_hobbies(*some_hobbies)
My hobbies: reading, writing, hiking, learning Python
Enter fullscreen mode Exit fullscreen mode

Now say we want a function enabling users to share their favorite things in various categories, but we don't know in advance how many categories a given user will select:

def my_faves(**favorites):
    print("My favorite things...")
    for category, fave in favorites.items():
        print(f"{category}: {fave}")
Enter fullscreen mode Exit fullscreen mode

Our function now accepts one or more keyword arguments:

>>> my_faves(Color='green', Fruit='persimmon')
My favorite things...
Color: green
Fruit: persimmon

>>> my_faves(Season='winter', Language='Python', Website='dev.to')
My favorite things...
Season: fall
Language: Python
Website: dev.to
Enter fullscreen mode Exit fullscreen mode

We can also call our function by passing it a dictionary, using similar double asterisk syntax:

>>> some_faves = {"Animal": "whale", "Summer Hobby": "hiking"}
>>> my_faves(**some_faves)
My favorite things...
Animal: whale
Summer Hobby: hiking
Enter fullscreen mode Exit fullscreen mode

A function may be defined with a mixture of formal parameters, variable-length parameters, and variable-length keyword parameters. When doing so, they must appear in the definition in the following order:

def a_function(arg, *args, **kwargs):
    ...
Enter fullscreen mode Exit fullscreen mode

More information can be found in the Python documentation.


Was this helpful? Did I save you some time?

🫖 Buy Me A Tea! ☕️


💖 💪 🙅 🚩
adamlombard
Adam Lombard

Posted on January 12, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related