forwarding *arg parameter

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sun Nov 5 12:22:51 EST 2006


On Sun, 05 Nov 2006 15:26:58 +0000, Tuomas wrote:

>  >>> def g(*arg):
> ...     return arg
> ...
>  >>> g('foo', 'bar')
> ('foo', 'bar')
>  >>> # seems reasonable

The function g:
- takes the arguments 'foo' and 'bar'
- collects them in a tuple named 'arg' = ('foo', 'bar')
- returns the tuple named arg


>  >>> g(g('foo', 'bar'))
> (('foo', 'bar'),)

The function g:
- takes the argument ('foo', 'bar')
- collects it in a tuple named 'arg' = (('foo', 'bar'),)
- returns the tuple named arg

The function is doing exactly the same as in the first case, except the
arguments are different.


>  >>> # not so good, what g should return to get rid of the outer tuple

Why do you want to? The way the function is now makes perfect sense. All
argument types are treated in exactly the same way:

g(string) => tuple containing string
g(float) => tuple containing float
g(int) => tuple containing int
g(list) => tuple containing list
g(instance) => tuple containing instance
g(tuple) => tuple containing tuple

You could write something like this:

def g(*arg):
    # Detect the special case of a single tuple argument
    if len(arg) == 1 and type(arg[0]) == tuple:
        return arg[0]
    else:
        return arg

but now tuple arguments are treated differently to all other data. Why do
you think you need that?


-- 
Steven




More information about the Python-list mailing list