recursive function call
Duncan Booth
duncan.booth at invalid.invalid
Tue Nov 8 05:37:37 EST 2005
Nicolas Vigier wrote:
> I have in my python script a function that look like this :
>
> def my_function(arg1, arg2, opt1=0, opt2=1, opt3=42):
> if type(arg1) is ListType:
> for a in arg1:
> my_function(a, arg2, opt1=opt1, opt2=opt2,
> opt3=opt3)
> return
> if type(arg2) is ListType:
> for a in arg2:
> my_function(arg1, a, opt1=opt1, opt2=opt2,
> opt3=opt3)
> return
> ... then here the real function code
>
> I'm new to python, so I was wondering if there is a better way to do
> that. The reason for a recursive function here is to be able to give
> lists for the first 2 args (I could as well use only a simple 'for'
> without a recursive call). The problem I have here, is that as I'm
> working on this script, I often change the prototype of the function,
> and each time I have to think about changing the recursive call too.
> Is there a way that I can do a recursive call and say something like
> "keep all the same arguments except this one" ?
>
This gets messy if the actual first two arguments could also be lists, do
you really want it to recurse again? I would handle this by having two
functions, one which takes simple arguments:
def my_function(a, b, opt1=0, opt2=1, opt3=42):
... the real function code ...
and one which takes your list arguments:
def my_function_for_sequences(seqA, seqB, *args, **kw):
for a in seqA:
for b in seqB:
my_function(a, b, *args, **kw)
That way you avoid any confusion over the argument types. It won't handle
the case where only one of a or b is a sequence, but you can handle that
easily enough by creating a list in the call.
It will also handle the case where you pass an iterable which isn't a list,
so you have more flexibility there. (Once you are used to Python you should
get a big red warning light going on in your head any time you see an
explicit test for a type: not all such cases are bad, but they often
indicate a code smell.)
More information about the Python-list
mailing list