• Python Snacks
  • Posts
  • Letting Python Do the Heavy Lifting: A Dive into *args and **kwargs

Letting Python Do the Heavy Lifting: A Dive into *args and **kwargs

Want more fexibility in your code? Leveraging *args and **kwargs may be the key.

You may have seen *args and **kwargs in Python functions/methods before like such:

def print_parameters(*args, **kwargs):
  print(f"Here are the arguments: {args}")
  print(f"Here are the keyword arguments: {kwargs}")

The parameters for this function makes the function dynamic to allow any number of arguments and keyword arguments to be passed in.

Here, I want to dive into what these parameters specifically and how you can leverage them to be able to make your code a bit better.

Article Contents

What exactly are *args and **kwargs?

As mentioned above, these are shorthand for “arguments” and “keyword arguments”.

You may have written code that looks something like this:

def my_new_function(
    param_1, # An argument (non-keyword)
    param_2 = None # A keyword argument
):
    print(f"{param_1} and {param_2}")

In this above scenario, param_1 is an argument. On the contrary, param_2 is a keyword argument.

While this approach works well for functions with a fixed number of parameters, there are situations where you may want your functions to accept an unknown number of arguments.

Leveraging *args and **kwargs in your functions gives you this flexibility, as we’ll see a bit later in this article.

A practical example of this are Python wrappers - you need to pass a variable number of arguments and keyword arguments into your wrapped function.

Understanding *args

When you have *args in your function, it can accept any number of positional arguments, which are stored in a tuple.

Because it’s stored inside of a tuple, you can iterate over it and access specific elements using indexing, slicing, or even passing them into another function.

Here’s an example of how you can use it:

def print_args(*args):
  print(args)

# Sample call:
#   print_args(1, "hello", 2, "bye")
#
# Output:
#   (1, 'hello', 2, 'bye')

Remember that order matters here!

Understanding **kwargs

Unlike *args, **kwargs can accept any number of keyword arguments, which are stored inside of a dictionary.

Similarly, you can iterate over the dictionary and access the key:value pair with dictionary logic. For example:

def print_kwargs(**kwargs):
  for key, value in kwargs.items():
    print(f"{key} -> {value}")

# Sample call:
#   print_kwargs(one = 1, two = 2, three = 3)
#
# Output:
#   'one' -> 1
#   'two' -> 2
#   'three' -> 3

An Example using *args and **kwargs

Now that we have a basic understanding on what these mean individually, let’s combine them into one function to see how we can leverage them.

In the example below, we’re renaming *args to be *items and **kwargs to be **details to be a bit more verbose with what we’re getting at.

If we write a function to process an order (aka, print what the order is), our function may look as such:

def process_order(order_id, *items, **details):
    print(f"Processing Order ID: {order_id}")
    print("Items in the order:")

    for item in items:
        print(f"- {item}")
    
    if details:
        print("\nAdditional details:")
        for key, value in details.items():
            print(f"{key.capitalize()}: {value}")

Where the items are the items listed inside of the order and details would be different details about the purchase and the customer themselves. So, for instance, if we have the following call:

# Sample call
process_order(
    12345,
    "Laptop", "Mouse", "Keyboard",
    shipping_address="123 Python Road",
    discount_code="SAVE20",
    gift_wrap=True 
)

Our output may look something like:

# Processing Order ID: 12345
# Items in the order:
# - Laptop
# - Mouse
# - Keyboard
#
# Additional details:
# Shipping_address: 123 Python Road
# Discount_code: SAVE20
# Gift_wrap: True

See if you can break down the code to determine which of the details are part of the arguments and which ones are keyword arguments.

📧 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

or to participate.