0

Is there a way to make a compound Python object immutable ‘in-depth’? That is, to disallow any change at any level to the object.

One can indeed make a deepcopy of the object to work with, but that can be costly. I'd like to see if one can make the compound object completely immutable, perhaps by recursively overriding the internal __setattr__ methods to emulate immutability.

An example would be a dictionary which has dictionaries and Numpy arrays as its values, or a Numpy array which stores Python objects as its elements.

This is related to the SO question, “How to make an immutable object in Python?”.

AlQuemist
  • 1,110
  • 3
  • 12
  • 22
  • Why would you want to do that? I don't see the use case for this. – Aran-Fey Jul 26 '18 at 13:59
  • @Aran-Fey: A use-case for me is to share _concurrently_ a (heavy) compound Python object between _more than one_ user-provided functions. The functions should not be able to mutate the objects in any way, in order to prevent data corruption. – AlQuemist Jul 27 '18 at 11:26
  • Fair enough. It definitely won't be easy though. Making mutable objects immutable isn't something you usually need to do; you'd generally make the classes immutable to begin with. – Aran-Fey Jul 27 '18 at 13:07

0 Answers0