I see that one way to use *arg in a function is to simply pass them on to
another function that perhaps will unpack the arguments:
###
def pass_along(func, *args):
return func(*args)
def adder(x,y):
return x+y
def suber(x,y):
return x-y
print pass_along(adder,1,2)
print pass_along(suber,1,2)
###
But there is another use that I am looking at right now (as encountered in the
turtle module) where the arguments are analyzed in the function and not passed
along. In such cases it seems like the first two lines of the function below
are needed to get the passed arg out of the tuple form that is created and into
the form expected in the function.
###
def goto(*arg):
if len(arg) == 1:
arg = arg[0]
x, y = arg
print x, y
goto(1,2)
pt = 1,2
goto(pt)
###
Without those first two lines, passing 'pt' as in the example results in a
runtime error since arg = ((1, 2),) -- a tuple of length 1 -- cannot be
unpacked into two items.
MY QUESTION: since the pass_along function will work with this unpacking of
length = 1 tuples and this is what you have to do anyway if you are going to
consume the tuple in a function (as in the goto function above) is there a
reason that this isn't automatically done for star arguments? Am I missing some
other usage where you wouldn't want to unpack the *arg? If not, would the
following "behind the scenes" behavior be possible/preferred?
###
def foo(*arg):
pass
###
automatically does this
###
def foo(*arg):
if len(arg) == 1:
arg = arg[0]
pass
###
Chris
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor