Tuomas wrote: > 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
Suppose you did actually want to do this you have chosen about the worst possible way: the use of global variables to condition function execution is a sure way to get into trouble. Consider if somebody else want to use your function: they also have to set a global in their program to avoid your function raising an exception. Fortunately Python has just the thing to make such horrors unnecessary: the default argument value. Try something like this (untested): def g(flattening=True, *arg): if flattening: arg = flatten(arg) return arg Obviously you could use either True or False for the default value. In the case above the function flattens by default. You could also, if you wished, have f() take the flattening argument, and always pass it to g(). Nothing very sophisticated here, just something to help you flex your growing Python and programming muscles. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list