1

I want to pass an argument from the first call of a recursive function down to the later ones:

Example:

def function(x):
    if base_case:
        return 4
    else:
        return function(x_from_the_first_call + x_from_this_call)

Is there any better way of doing this than a closure?

E.g.

def function(outer_x):
    def _inner(x)
        if base_case:
            return 4
        else:
            return function(outer_x + x)
    return _inner(outer_x)
3
  • 1
    Can you just make your function accept two arguments? Then just pass the two values separately (with a default value for the initial call) and add them inside the function. Commented Jan 17, 2014 at 20:55
  • 1
    @BrenBarn Would you consider that cleaner than a closure? My problem with doing that is it causes there to be an extra parameter which could confuse anyone calling the function who is unaware of the implementation, which strikes me as a bad thing. Commented Jan 17, 2014 at 20:58
  • 2
    I usually do it with a separate named argument that defaults to None. And "since we're all consenting adults" in python, presumably any caller who changes that arg has a good reason for doing so. Commented Jan 17, 2014 at 21:14

1 Answer 1

1

If you will change x somehow in function, then this should work i think:

def function(x, *args):
    if base_case:
        return 4
    else:
        new_x = x+1 # some change to x

        if args:
            # in args all previous x values

        # remove if in case if you need all previous values
        if not args:
            args.append(x)

        return function(new_x, *args)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.