Question about implementing immutability
Calvin Spealman
cspealma at redhat.com
Wed Nov 21 15:36:15 EST 2018
If you want to create your own immutable class, maybe inherit from a
namedtuple?
On Wed, Nov 21, 2018 at 11:45 AM Iwo Herka <iwoherka at gmail.com> 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)
> raise AttributeError()
>
> What do you think of this approach? Is there a better one?
> Thanks.
>
> Sincerely,
> Iwo Herka
> --
> https://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list