[Python-ideas] Unpack of sequences

Steven D'Aprano steve at pearwood.info
Wed Aug 29 20:20:01 CEST 2012

On 30/08/12 03:28, Guido van Rossum wrote:

> Sounds to me like there are so many potential variations here that
> it's probably better not to add a language feature and let users write
> what they want. (My personal variation would be to use m.get(k)
> instead of m[k].)

The obvious problem is that without language support, they have to repeat
the key names.

We've been here before with decorators, where you had to repeat the
function name three times before the @ syntax was introduced.

It's not too bad for namedtuple, because you only have to repeat one name:

spam = namedtuple('spam', field_names)

although that's still a mild code smell. But once you have multiple targets,
it gets ugly soon, e.g. the typical enumeration (anti-)pattern:


Maybe it's time to tackle this once and for all and find a way to access
the left-hand side names from the right-hand side. Assuming that's even
possible at all, here's a wild suggestion: expand @ on the right-hand
side to a quoted list of the names from the left:

# Enumerations

# Dict unpacking
a, b, x, y = *[mapping.get(name) for name in @]

# namedtuple
spam = namedtuple(@, field_names)

Obviously this isn't a fully-fleshed out idea. I'm not sure what the
target @ should do here:

dict['key'], list[0], obj.attr, x = [something(name) for name in @]

1) Expand to ['key', '0', 'attr', 'x'] ?

2) Expand to ["dict['key']", "list[0]", "obj.attr", "x"] ?

Or what happens if you have multiple = signs?

a, b, c = x, y, z = @

But the easy way out is to only allow @ for the simple case and
raise an exception for anything else. We could always add support
for the more complicated cases in the future.


More information about the Python-ideas mailing list