default tuple unpacking?

Peter Hansen peter at engcorp.com
Tue Sep 3 23:58:39 EDT 2002


Peter Hansen wrote:
> Huaiyu Zhu wrote:
> 
>> It is often very convenient to have default arguments such as
>>
>>     def func(a, b, *c): ...
>>
>> Is there a way to use this in statements too?  Examples:
>>
>>     a, (b, *c), *d = e

Hmm... I think there might be an inconsistency or an unexpected
result in this.  What if e already contains a tuple?

   e = (1, 2, 3)
   *a = e        # a is ((1, 2, 3), )

That seems sensible, and it's just what happens if you pass
"e" in to a function defined as "def func(*a)".

Now what about this:

   a, *b = e     # a is 1, b is (2, 3)

That's one possible result, and presumably the one you want with
this syntax, but it's not what you'd get with the function syntax:

   def func(a, *b):
     print a
     print b

   func(e)

Here of course you get (1, 2, 3) in "a" and () in b.  To get the
same as the proposed syntax above, you can't pass in a tuple, but
have to pass the parameters separately:

   func(1, 2, 3)  # now a is 1, b is (2, 3)

The problem is that in function calling, you can pass in a single
tuple, which is one argument, or you can pass the elements separately
as multiple arguments, which is when the special * syntax kicks in.

When doing assignment with tuples you don't have the same two options:

   a, *b = 1, 2, 3

is the same as

   a, *b = (1, 2, 3)

So maybe this won't fly.  Comments?

-Peter




More information about the Python-list mailing list