A Python Sequence (Un)Packing Primer

30 Minute Talk
Saturday at 11:00 am in Orchid Ballroom West

What happens in Python when you type things like?

def spam():
    return 1,2,3

a, b, c = spam()
def foo(*args, **kwargs):
   ...
for name, value in some_dict.items():
my_dict = some_func_that_returns_a_dict()

some_other_func(**my_dict)

In this talk, we'll examine Python's ability to unpack values from (or sometimes pack them into) sequences. We'll see how that capability powers a host of powerful Python idioms. We'll also look at some less commonly used syntax to unpack sequences into complex data structures. Used judiciously, these techniques can simplify your code. Last, we'll talk about mental models, and why it's important to develop good mental models for what's happening "under-the-hood" when we write Python. Well show what can (and did) happen when having the wrong mental model of unpacking syntax lead to a bug. We'll look at code that shows the problem, discuss what's really happening, then use the Python bytecode disassembler to confirm our intuition.

Although this talk briefly uses the Python bytecode disassembler, it's aimed at beginners (though not complete novices) who want to write more idiomatic Python, and develop a better intuition for what's really happening in the interpreter when their code runs.

Presented by

Brian Costlow