Skip to content Skip to sidebar Skip to footer

Persistent Objects In Recursive Python Functions

I am trying to write a recursive function that needs to store and modify an object (say a set) as it recurses. Should I use a global name inside the function? Another option is to

Solution 1:

Just pass through your persistent object through the recursive method.

defrecursivemethod(obj_to_act_on, persistent_obj=None):

    if persistent_obj == None:
        persistent_obj = set()

    # Act on your objectreturn recursivemethod(newobj, persistent_obj)

Solution 2:

Objects are passed by reference. If you're only modifying an object, you can do that from within a recursive function and the change will be globally visible.

If you need to assign a variable inside a recursive function and see it after the function returns, then you can't just assign a local variable with =. What you can do is update a field of another object.

classAccumulator: passdeffoo():
    # Create accumulator
    acc = Accumulator()
    acc.value = 0# Define and call a recursive function that modifies accumulatordefbar(n):
        if (n > 0): bar(n-1)
        acc.value = acc.value + 1
    bar(5)

    # Get accumulatorreturn acc.value

Solution 3:

Pass the set into the recursive method as an argument, then modify it there before passing it to the next step. Complex objects are passed by reference.

Solution 4:

If it's a container (not an immutable data type), you can pass the object through:

import random

deffoo(bar=None, i=10):
    if bar isNone:
        bar = set()
    if i == 0:
        return bar
    bar |= set(random.randint(1, 1000) for i in xrange(10))
    return foo(bar, i - 1)

random_numbers_set = foo()

(Don't ask me what that's meant to do... I was just typing random things :P)

Solution 5:

If the object you pass is mutable then changes to it in deeper recursions will be seen in earlier recursions.

Post a Comment for "Persistent Objects In Recursive Python Functions"