Using Tuple and Dict as Args and Kwargs in Python

In line with making apps flexible, Python really, really makes it super easy to accomplish that.

And this will be (sort-of) a follow up on my previous blog about args and kwargs. If you haven’t read that, here it is:

Related blog to this post. Read this first if you’re not familiar with args and kwargs

From the previous blog, we’ve seen how to pass positional and keyword arguments to a Python function.

Now, we’re going to use another powerful feature of Python, and that is it’s ability to “expand” iterables like Tuple and Dictionary when passing them to a function.

The asterisk actually instructs Python to expand the values to their individual values and knowing this, we can standardize how we call functions by first collecting positional data into a tuple and keyword arguments into a dictionary.

Here’s a sample function that a financial institution might have:

def create_account(name, initial_deposit, type='savings', with_passbook=False):
    """ mock function to create a bank account """

    print(f"Creating a new {type.title()} account for {name.title()}")
    print(f"\tInitial Deposit = {initial_deposit}")
    
    if with_passbook:
        print(f"\tThis will have a passbook")
    else:
        print(f"\tThis will not have a passbook")

This function as 2 positional arguments (name and initial_deposit). It also has 2 keyword arguments (type and with_passbook).

We know how to call this the typical way, but this blog is not about that. We’re going to call this differently.

First, let’s assemble the information it requires:

# define client info as tuple (list would also work)
client_info = ('John Doe', 2000)

# set the optional params as dictionary
acct_options = {
    'type': 'checking',
    'with_passbook': True
}

Now here’s the fun and cool part 🙂
We’re going to pass these 2 data structures to the function by adding a single and double asterisk to them respectively:

create_account(*client_info, **acct_options)

The tuple is prefixed with a single asterisk, which will be expanded to the corresponding positional arguments of the function.

The dictionary is prefixed with double asterisk, which will be expanded into keyword arguments based on their key name.

Here’s the link for the source codes in GitHub:

https://github.com/vegitz/codes/tree/master/0015%20Using%20Tuple%20and%20Dict%20as%20Args%20and%20Kwargs

Leave a Comment