forwarding *arg parameter

Tuomas tuomas.vesterinen at pp.inet.fi
Mon Nov 6 14:03:55 CET 2006


Steven D'Aprano wrote:
> On Sun, 05 Nov 2006 19:35:58 +0000, Tuomas wrote:
> 
> 
>>Thanks. My solution became:
>>
>> >>> def flattern(arg):
>>...     result = []
>>...     for item in arg:
>>...         if isinstance(item, (list, tuple)):
>>...             result.extend(flattern(item))
>>...         else:
>>...             result.append(item)
>>...     return tuple(result)
>>...
>> >>> def g(*arg):
>>...     arg = flattern(arg)
>>...     return arg
>>...
>> >>> def f(*arg):
>>...     return g(arg)
>>...
>> >>> f('foo', 'bar')
>>('foo', 'bar')
> 
> 
> 
> That's the most complicated do-nothing function I've ever seen. Here is a
> shorter version:
> 
> def shortf(*args):
>     return args
> 
> 
> 
>>>>f('foo', 'bar')
> 
> ('foo', 'bar')
> 
>>>>shortf('foo', 'bar')
> 
> ('foo', 'bar')
> 
> 
>>>>f(1,2,3,4)
> 
> (1, 2, 3, 4)
> 
>>>>shortf(1,2,3,4)
> 
> (1, 2, 3, 4)
> 
> 
>>>>f({}, None, 1, -1.2, "hello world")
> 
> ({}, None, 1, -1.2, 'hello world')
> 
>>>>shortf({}, None, 1, -1.2, "hello world")
> 
> ({}, None, 1, -1.2, 'hello world')
> 
> Actually, they aren't *quite* identical: your function rips lists apart,
> which is probably not a good idea.
> 
> 
>>>>f("foo", [1,2,3], None) # three arguments turns into five
> 
> ('foo', 1, 2, 3, None)
> 
>>>>shortf("foo", [1,2,3], None) # three arguments stays three
> 
> ('foo', [1, 2, 3], None)
> 
> 
> 
> I still don't understand why you are doing this. Can we have an example of
> why you think you need to do this?

If i redefine the function g the difference comes visible:

  >>> def g(*arg):
...     if with_flattern: arg=flattern(arg)
...     return arg

 >>> with_flattern=False
 >>> f('foo', 'bar')
(('foo', 'bar'),)
 >>> with_flattern=True
 >>> f('foo', 'bar')

If you read the whole chain you find out what we were talking of.

TV



More information about the Python-list mailing list