Python: Automatic Argument Unpacking from a Dictionary

1 min read

Programming often involves creating configuration objects/dicts and passing them around to functions. Let's say we want to pass the following configuration dict to a function:

config = {
    'prop_a': 'foo',
    'prop_b': 'bar'

Usually, a function that consumes this configuration dict would either expect a single parameter:

def do_something(config):
    prop_a = config['prop_a']
    prop_b = config['prop_b']
    # do something with the props

Or would rather have them listed as separate params, but those have to be manually read out of config when calling the function:

def do_something(prop_a, prop_b):
    # do something with the props
do_something(prop_a=config['prop_a'], prop_b=config['prop_b'])    

What if we didn't have to explicitly unpack each and every property? If the keys in the dictionary exactly match the names of parameters expected by the function, one could simply use the ** operator and those would be unpacked and assigned automatically:

def do_something(prop_a, prop_b):
    # do something with the props


See also

Unpacking Argument Lists

Related Articles

Elixir Tip: Case vs. With
3 min read
Elixir Is Not Ruby. Elixir Is Erlang
2 min read

Write Stupid Code

This is very much a re-interpretation of a post by Thorsten Ball, written back in 2015. Like him, I too

1 min read