[issue35527] Make fields selectively immutable in dataclasses

Rémi Lapeyre report at bugs.python.org
Tue Jan 1 19:12:54 EST 2019


Rémi Lapeyre <remi.lapeyre at henki.fr> added the comment:

Hi @rhettinger, this is similar to #33474.

I started working on an implementation of this.

With the implementation you propose, if a field has both init=True and frozen=True, it may be set after the creation of the instance:

        @dataclass
        class Person:
            ssn: int = field(init=False, frozen=True)
            name: str

        p = Person(name='foo')
        p.name = 'bar'
        p.ssn = 1234

Wouldn't this conflict with the purpose of safe hashing?

I think it would need __setattr__ to be:

      def __setattr__(self, attr, value):
            if attr in {'ssn', 'birth_city'}:
                 raise TypeError(
                     f'{attr!r} is not settable after initialization')
            return super(cls, self).__setattr__(self, name, attr)

wouldn't it?

----------
nosy: +remi.lapeyre

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue35527>
_______________________________________


More information about the Python-bugs-list mailing list