You may have seen the following syntax before:

def my_function(*args, **kwargs):
    print(args)
    print(kwargs)

There’s some “advanced” syntax that’s here: *args and **kwargs. You can think of these as parameters to make the function parameters to be dynamic. That is, you can pass in an unlimited number of positional arguments and keyword arguments!

» For reference, arguments are positional and generally follow the opening parenthesis, whereas keyword arguments have an equal (=) sign.

example("hello") # Has 1 argument
example(phrase = "world") # has 1 keyword argument

# Has both an argument and a keyword argument
example("hello", phrase = "world")

Leveraging both *args and **kwargs allows you to keep you functions flexible and backwards compatible as you build your software.

What are these stars ahead of args and kwargs?

Trey Hunner explains what these are in really good detail, but in short they are a way to “unpack” items in a function call.

For instance, if you have a list that you’d like to print, you could write it as such:

numbers = [2, 1, 3, 4, 7]
print(
  numbers[0], 
  numbers[1],
  numbers[2],
  numbers[3],
  numbers[4]
)

# Output: 2 1 3 4 7

» Note: Notice that our output isn’t a list - we’re printing each number individually. If we did print(numbers), we’d have [2, 1, 3, 4, 7] as our output, not the output above.

While this isn’t inherently wrong, it’ll break if you remove an index in the numbers list. Instead, you can “unpack” it:

numbers = [2, 1, 3, 4, 7]
print(*numbers) # Output: 2 1 3 4 7

We can continue to do this for different sizes of lists without ever breaking our code:

items = ["hello", "goodbye"]
print(*items) # Output: hello goodbye

items = ["one", 1, "Python", "Snacks"]
print(*items) # Output: one 1 Python Snacks

items = []
print(*items) # Output: <blank>

» Note: the single asterisk is used for unpacking lists and tuples, where as a double asterisk is used for dictionaries, which is demonstrated below.

Similar with **kwargs, you’ll use this when you want to unpack a dictionary:

state_capitals = {
   "Alabama" : "Montgomery",
   "Florida" : "Tallahassee",
   "Georgia" : "Atlanta"
}

def print_state_capitals(**kwargs):
    for state, capital in kwargs.items():
        print(f"The capital of {state} is {capital}")

print_state_capitals(**state_capitals)

# Output:
# The capital of Alabama is Montgomery
# The capital of Florida is Tallahassee
# The capital of Georgia is Atlanta

Using args and kwargs as “unlimited” parameters

The examples above show how you’d use it for the specific data structure - lists for *args and dicts for **kwargs. But in practicality, you might not use it like this. Instead, you may use it as a way to have “unlimited” parameters:

def log_event(event_type, *args, **kwargs):
    print(f"Event: {event_type}")
    print(f"Details: {args}")
    print(f"Metadata: {kwargs}")

log_event(
    "user_login", # positional -> event_type
    "192.168.1.1",  # extra positionals -> args
    "Chrome",       # extra positionals -> args
    user_id=42,          # keyword -> kwargs
    session_id="abc123"  # keyword -> kwargs
)

Now we can log an event with unlimited details and metadata by passing them in as parameters and keyword arguments!

I’ve generally used *args and **kwargs for this purpose - I’ve ran into situations where I’ve had to pass unknown or a dynamic number of parameters into a function.

Happy coding!

📧 Join the Python Snacks Newsletter! 🐍

Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:

  1. Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.

  2. Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.

  3. Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.

You can unsubscribe at any time.

Interested in starting a newsletter or a blog?

Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.

If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.

This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.

Reply

Avatar

or to participate

Keep Reading