Motheus
Motheus

Reputation: 543

Python dict as local, not reference

I'm trying to get my little script working but I don't know what the problem is.

One of the methods will modify my test dict var even if I don't return it. I mean, I want to work with that locally and NOT to return the value. This is not my actual code but you can be sure that it is representative.

>>> class check:
...   def pathgen(self,test):
...     test['a']=0
...     print test
...   def assign(self):
...     test={'a':1}
...     self.pathgen(test)
...     print test #WILL PRINT 0
... 
>>> a=check()
>>> a.assign()
{'a': 0}
{'a': 0}

Upvotes: 3

Views: 258

Answers (1)

Steven Rumbalski
Steven Rumbalski

Reputation: 45562

If you want changes to an object to be local to the function that changes it you need to copy the object. You can either copy the dictionary upon calling:

self.pathgen(dict(test))

or copy within the callee.

def pathgen(self, test):
    test = dict(test)
    ...

Upvotes: 3

Related Questions