[Python-ideas] Unpack of sequences

Guido van Rossum guido at python.org
Wed Aug 29 20:21:55 CEST 2012

On Wed, Aug 29, 2012 at 11:07 AM, Alexander Belopolsky
<alexander.belopolsky at gmail.com> wrote:
> On Wed, Aug 29, 2012 at 1:28 PM, Guido van Rossum <guido at python.org> wrote:
>> it's probably better not to add a language feature and let users write
>> what they want.
> How can users write a solution that does not require repetition of
> variable names?

Maybe they can't. So what? There's a limit to the applicability of
DRY. Most solutions I've seen for this particular set of issues are
worse than the problem they are trying to solve.

Another antipattern IMO is sometimes seen in constructors:

class C:
  def __init__(self, **kwds):

This has nothing to recommend it.

> Of course I can write something like
> a, b, c = [m.get(x) for x in ('a', 'b', 'c')]
> but when I have more and longer names, this gets tedious.
> As far as syntax goes, I also find a, b, c = **m somewhat unintuitive.
>  I would prefer
> {a, b, c} = m

But {a, b, c} is already a set. I'd expect set-like semantics, perhaps
assigning the keys of a 3-element set in arbitrary order to the
variables a, b and c.

> and
> {a, b, c, **rest} = m.
>> I'd be even less sure about something syntactically similarly plausible like
>> self.a, self.b, self.c = **foo
> I don't think unpacking into attributes is as useful as unpacking into
> locals.  Object attribute lists are often available programmatically
> and it is a simple matter to supply an _update() function that can be
> used as self._update(locals()) after values have been assigned to
> locals or simply use self._update(m) directly.

Another antipattern.

> (I recall that something like {'a': x, 'b': y} = m has been suggested
> and rejected in the past.  That syntax also required explicit
> specification of the keys to be unpacked.)

I don't believe a valid syntax proposal can come out of this thread.

--Guido van Rossum (python.org/~guido)

More information about the Python-ideas mailing list