DEV Community

Discussion on: Mutable Default Arguments in Python

 
rhymes profile image
rhymes

Honestly? I don't think so.

It might be better to use a functional approach and limit sharing data. For example, using Ruby:

2.6.5 :001 > a = {key: "value"}
 => {:key=>"value"}
2.6.5 :002 > b = a.merge(foo: :bar)
 => {:key=>"value", :foo=>:bar}
2.6.5 :003 > a
 => {:key=>"value"}
2.6.5 :004 > b
 => {:key=>"value", :foo=>:bar}
2.6.5 :005 > def transform_data(data)
2.6.5 :006?>   data.merge(new: :data)
2.6.5 :007?>   end
 => :transform_data
2.6.5 :008 > c = transform_data(b)
 => {:key=>"value", :foo=>:bar, :new=>:data}
2.6.5 :009 > [a, b, c]
 => [{:key=>"value"}, {:key=>"value", :foo=>:bar}, {:key=>"value", :foo=>:bar, :new=>:data}]

as you can see I never change a or b. I just create new objects, I never change the content of the variable.

This is similar to how pure functional languages work or languages like Erlang where variables are immutable, so once they have a value, they'll keep that for their entire life.