You should get Packing with Python 3.5

Published: November 22, 2015

The new Python 3.5 unpacking syntax makes a programmer's life much easier.

Have you ever been in the following situation?

def froblog(**kwargs):
    print(kwargs.items())

some_kwargs = {
    'frob': 'lob',
    'frux': 'flib',}

other_kwargs_from_somewhere_else = {
    'floxblum': 'qux',}

more_kwargs = {
    'flipblip': 'foobar',}  # Etc., I think you get the point

some_kwargs.update(other_kwargs_from_somewhere_else)
some_kwargs.update(more_kwargs)

froblog(**some_kwargs)
dict_items([('flipblip', 'foobar'), ('frob', 'lob'), ('floxblum', 'qux'),
('frux', 'flib')])

Now, if we want to reuse some_kwargs, they are tainted with the otherkwargs. Of course, we could have constructed a new dict and used that to pass all the dict key-value pairs that we want to pass. But either way it feels messy.

The solution

Python 3.5 introduced Python Enhancement Proposal (PEP) 0448titled Additional Unpacking Generalizations. Assuming you are using the samefroblog method, you can write the following code using the new unpacking generalizations:

some_kwargs = {
    'frob': 'lob',
    'frux': 'flib',}

other_kwargs_from_somewhere_else = {
    'floxblum': 'qux',}

more_kwargs = {
    'flipblip': 'foobar',}  # Etc., I think you get the point

froblog(**some_kwargs, **other_kwargs_from_somewhere_else, **more_kwargs)

This outputs the same dict_items as before:

dict_items([('flipblip', 'foobar'), ('frob', 'lob'), ('floxblum', 'qux'),
('frux', 'flib')])

This is considerably cleaner. For more awesome unpacking madness, do check out the PEP 0448 documentexamples.

Happy unpacking, dear reader.

Tags

I would be thrilled to hear from you! Please share your thoughts and ideas with me via email.

Back to Index