Question about implementing immutability

Dan Sommers 2QdxY4RzWzUUiLuE at potatochowder.com
Wed Nov 21 15:22:02 EST 2018


On 11/21/18 11:45 AM, 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)
>          raise AttributeError()
> 
> What do you think of this approach? Is there a better one?
> Thanks.
That depends on your definition of immutability.

If an instance of your class contains a list, and you change one
of the elements of that list, then the instance's __setattr__
never comes into play:

     x = AllegedlyImmutableObject(list('a', 'b', 'c'))
     x.some_list[4] = 0



More information about the Python-list mailing list