(Explain why this feature or enhancement should be implemented and how it would be used.
Add examples, if applicable.)
In the autogenerate __setattr__ and __delattr__, they have a sanity check at the beginning of the method. For example:
def__setattr__(self, name, value):
iftype(self) is {{UserType}} ornamein ({{atupleoffieldnames}}):
raiseFrozenInstanceError(f"cannot assign to field {name!r}")
super(cls, self).__setattr__(name, value)
If someone inherits the frozen dataclass, the sanity check will take $O(n)$ time on the tuple__contains__(...) and finally calls super().__setattr__(...). For example:
@dataclass(frozen=True)classFrozenBase:
x: inty: int
... # N_FIELDSclassFoo(FrozenBase):
def__init__(self, x, y, somevalue, someothervalue):
super().__init__(x, y)
self.somevalue=somevalue# takes O(N_FIELDS)self.someothervalue=someothervalue# takes O(N_FIELDS) time againfoo=Foo(1, 2, 3, 4)
foo.extravalue=extravalue# takes O(N_FIELDS) time again
changed the title [-][Enhancement] Speed up sanity check for `__setattr__` and `__delattr__` for frozen `dataclass`es[/-][+][Enhancement] Speed up setting and deleting mutable attributes on non-dataclass subclasses of frozen dataclasses[/+]on Mar 10, 2023
Activity
AlexWaygood commented on Mar 10, 2023
Here is a benchmark that seems more reflective of a real-world use case, that shows a clear speedup from this proposed change:
ericvsmith commented on Mar 10, 2023
The idea seems reasonable. I'll look at the PR.
gh-102578: Optimise setting and deleting mutable attributes on non-da…
ericvsmith commented on Mar 11, 2023
Thanks, @XuehaiPan !
pythongh-102578: Optimise setting and deleting mutable attributes on …