Question about implementing immutability
Thomas Jollans
tjol at tjol.eu
Thu Nov 22 06:14:16 EST 2018
On 2018-11-21 17:45, Iwo Herka wrote:
> Hello,
>
> Let's say I want to implement immutability for user-defined class.
> More precisely, a class that can be modified only in its (or its
> super-class') __init__ method. My initial idea was to do it the
> following fashion:
>
> def __setattr__(self, *args, **kwargs):
> if sys._getframe(1).f_code.co_name == '__init__':
> return super().__setattr__(*args, **kwargs)
I don't like this. First of all, it's needlessly cryptic, and secondly
this allows other classes' __init__s to set attributes.
I might try setting a self._fixed flag at the end of init and do a check
if getattr(self, '_fixed', False):
raise TypeError(f"'{type(self)}' is immutable")
but this presumably comes with other problems.
> raise AttributeError()
This should be TypeError.
More information about the Python-list
mailing list