0

Okay, so I know this sounds like it's about Mutable default arguments but I wonder if there is a different explanation since the attribute is dict but no default is definied.
My code is similar to this:

params_dict = {'this_parameter': 15}

class SomeClass:
   def __init__(self, params):
       assert isinstance(params, dict)
       self.config = params

   def change_parameter(self, value):
       self.config['this_parameter'] = value

When I initialize a = SomeClass(params_dict) and then

b = SomeClass(params_dict)
b.change_parameter(100)

and then a.config it prints {'this_parameter: 100}. To me this looks like the "bug" all beginners see sooner or later with the mutable default arguments, but since I didn't use defaults I was wondering how to fix this.
(I wouldn't have considered myself a beginner anymore until today, but now I do again, so please bear with me!

frfritz
  • 41
  • 1
  • 7
  • 3
    *this sounds like it's about Mutable default arguments* .. it's actually the less-surprising relative of mutable default arguments: mutable arguments. – wim Dec 01 '20 at 19:31
  • @wpercy it does indeed for the example I gave here, but currently I am unable to do make it work for the real code... I'll see if I can work it out otherwise I'll have to come back! – frfritz Dec 01 '20 at 19:48
  • See [Deep copy of a dict in python](https://stackoverflow.com/questions/5105517/deep-copy-of-a-dict-in-python). – jarmod Dec 01 '20 at 19:51
  • @jarmod yes, this actually fixed it even though I don't understand why in the example given here the line ```params=dict(params)``` is enough and in my code it's not. – frfritz Dec 01 '20 at 20:19
  • Using `d1=dict(d2)` will create a shallow copy of `d2`. If you don't have compound objects within `d2` then it's as effective as a deep copy afaik and you can safely mutate `d1` without impacting `d2`. – jarmod Dec 01 '20 at 20:46

0 Answers0