Home > Mobile >  Differentiate nested self keyword in recursive instance methods
Differentiate nested self keyword in recursive instance methods

Time:10-23

So the template of my code looks like this :

class Foo:
    def __init__(self, params):
        self.params = params #a dictionary
    
    def recursive_iteration(self, buffer):
        if buffer :
            #do something
            self.params['new_field'] = "new_value"

        else :
            for i in range(2): 
                new_params = self.params
                new_params['some_field'] = another_value #changing with i
                Foo(new_params).recursive_iteration(True)

The problem I encounter is that when recursive_iteration is called inside another recursive_iteration then there are two self variables that exist within a different (but nested) scope.

And during the second iteration of the for loop (i=1): self.params has the field 'new_field' which means the outer scope self was the one modified.

Did i just flaw my code and should rework the model ?(I could go functional only but this is partially existing code)

My question is : Can I precise which self I want to be modified with regard to their scope?

EDIT : The issue comes from the shallow copy of self.params. All the time the same dictionnary is modified. It's not about the scope of the variables. Change new_params = self.params to new_params = self.params.copy() to solve the issue.

CodePudding user response:

The reason why you get a new nested scope is that you create a new Foo with Foo(new_params).recursive_iteration(True)

If you want this to be recursive, and call recursive_iteration() on the same object, then you need to call it this way:

self.recursive_iteration(True)

CodePudding user response:

Solution : The comments under my post solved the issue.

Gist of it : the issue comes from the shallow copy of self.params. All the time the same dictionnary is modified. It's not about the scope of the variables. Change new_params = self.params to new_params = self.params.copy() to solve the issue.

Problem solved.

  • Related