Tuples in function argument lists

S

Steven D'Aprano

I'm trying to understand the use of tuples in function argument lists.

I did this:
.... print a, b, c
.... Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in tester
TypeError: unpack non-sequence

That was obvious result.
ab a b

And so were those.

Then I tried this:
.... 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?

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

Robert Kern

Steven said:
I'm trying to understand the use of tuples in function argument lists.

I did this:


... print a, b, c
...


Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in tester
TypeError: unpack non-sequence

That was obvious result.


1 2 3


ab a b

And so were those.

Then I tried this:


... 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
(e-mail address removed)

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,142
Latest member
arinsharma
Top