Steven D'Aprano wrote:
> I'm trying to understand the use of tuples in function argument lists.
> 
> I did this:
> 
>>>>def tester(a, (b,c)):
> 
> ...     print a, b, c
> ... 
> 
>>>>tester(1, 2)
> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 1, in tester
> TypeError: unpack non-sequence
> 
> That was obvious result.
> 
>>>>tester(1, (2, 3))
> 
> 1 2 3
> 
>>>>tester('ab', 'ab')
> 
> ab a b
> 
> And so were those.
> 
> Then I tried this:
> 
>>>>def tester(a, (b,c)=None):
> 
> ...     if (b,c) is None:
> ...             print a, None
> ...     else:
> ...             print a, b, c
> 
> Needless to say, it did not do what I expected it to do. I didn't expect
> it to either :-)
> 
> I tried looking at the language reference here:
> 
> http://docs.python.org/ref/function.html
> 
> but I can't seem to find anything in their that says that tuples-as-args
> are legal. Am I misreading the docs, or is this accidental behaviour that
> shouldn't be relied on?

Tuples-as-arg are legal. Tuple-as-keyword, too *if* the default value is 
something that can actually unpack to a tuple. A default of None is...silly.

In [6]: def tester(a, (b,c)=(1,2)):
    ...:     print a,b,c
    ...:

In [7]: tester(1)
1 1 2

Tuple-as-arg is probably pretty safe. Tuple-as-keyword, possibly 
not-so-much.

> Does anyone use this behaviour, and if so, under what circumstances is it
> useful?

import math
def distance((x1,y1), (x2,y2)):
     return math.sqrt((x2-x1)**2 + (y2-y1)**2)
distance(point1, point2)

Personally, I prefer to explicitly unpack the tuple in the function body.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to