I'm curious about this as well. Would it make sense to have a separate method .with_defaults, that checks the mutability (i.e. .frozen?) of its arguments?
If the intention is for Data to be "deeply" immutable, I could see this making sense. Then again, I'm not sure if there is a way to detect mutability of all objects "belonging to" a given parent object. I guess if there were such a way, it would have been included in Data already, as a way to enforce its immutability.
Perhaps this sort of thing should exist in ActiveSupport instead, or as a gem, since its immutability checking cannot be guaranteed to work in all cases (but could be written to work for most). This is effectively the same problem as Python has with mutable default arguments.
To clarify what I mean, this is a (very rough) demonstration:
classDatadefself.with_defaults(*symbols,**defaults,&block)defaults&.each{|key,value|raiseArgumentError,"#{key} must be immutable"unlessRactor.shareable?(value)}Data.define(*(symbols+defaults.keys))do@@defaults=defaultsclass_eval(&block)ifblockdefinitialize(**kwargs)@@defaults.eachdo|key,value|kwargs[key]=valueunlesskwargs.key?(key)endsuper(**kwargs)endendendendPoint=Data.with_defaults(:x,:y,z: [].freeze)dodef+(other)=self.class.new(self.x+other.x,self.y+other.y)endp1=Point.new(x: 1,y: 2)p2=Point.new(x: 3,y: 4)p3=p1+p2
This isn't meant to be an actual proposal (lots of holes in this) - but, conceptually, I'm curious if the Ractor's concept of shareable? could or should be applied to Data, since it is supposed to be immutable.
I've found the need for something like this as well, I have a use case where it's getting repetitive and distractingly verbose to build out the Data blocks just for a number of defaults. The mutable defaults is a really good point, though it's not too dissimilar from existing behavior in Ruby's Hash with defaults --
h=Hash.new([])h[1]<<'foo'h[2]#=> ['foo']
So in a sense there is prior art here and a pattern that Rubyists already have to be aware of.
As a programmer, I can imagine the convenience of this default value for Data attributes, but as @zverok (Victor Shepelev) mentioned, I can also imagine the trouble caused by this (just like Python's famous optional argument issue).
So as a conclusion, we do not adopt this proposal.