default tuple unpacking?

Bengt Richter bokr at oz.net
Wed Sep 4 06:38:34 CEST 2002


On Tue, 03 Sep 2002 23:58:39 -0400, Peter Hansen <peter at engcorp.com> wrote:

>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
No, I think you'd want it to match the function effect
>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
Fine
>same as the proposed syntax above, you can't pass in a tuple, but
>have to pass the parameters separately:
but you can separate them by unpacking with '*'
>
>   func(1, 2, 3)  # now a is 1, b is (2, 3)
>
You can write the call as
    func(*e)
>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.
>
Kick it in on the calling side if that's what you want.
>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?
>

With function calling, '*' gets you packing or unpacking depending on context.
Why not also for the above? I.e.,
   a, *b = 1, 2, 3    # => a is 1, b is (2, 3)
and 
   a, *b = (1, 2, 3)  # => a is (1, 2, 3), b is ()
but
   a, *b = *(1, 2, 3) # => a is 1, b is (2, 3)
much as in

 >>> def foo(a,*b): print 'a is %s, b is %s' % (a,b)
 ...
 >>> foo(1,2,3)
 a is 1, b is (2, 3)
 >>> foo((1,2,3))
 a is (1, 2, 3), b is ()
 >>> foo(*(1,2,3))
 a is 1, b is (2, 3)

and

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

but

 >>> f=(1,2)
 >>> foo(f,3,4)
 a is (1, 2), b is (3, 4)
 >>> foo(*f,3,4)
   File "<string>", line 1
     foo(*f,3,4)
            ^
 SyntaxError: invalid syntax
 >>> foo(3,4,*f)
 a is 3, b is (4, 1, 2)

Hm. Why no unpacking at the front? (Ok, it's easier not to ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list