'isimmutable' and 'ImmutableNester'

Frank-Rene Schäfer fschaef at gmail.com
Tue Nov 12 12:10:21 CET 2013

> So how do you figure out whether something's immutable or not? Are you
> going to ask the object itself? If so, stick with __hash__, and just
> follow the rule that mutable objects aren't hashable - which is, if
> I'm not mistaken, how things already are. And if not, then how? How
> will you know if something has mutator methods?

Admittedly, I have no knowledge about the python implementation. A possible
way would be to say:

    def isimmutable(this):
         if isinstance(this, tuple):
              for x in this:
                  if not isimmutable(x): return False
              return True
         return isisintance(this, (int, str, ImmutableNester))

The ImmutableNester special class type would be a feature to help checks
to avoid recursion. Objects of classes derived from ImmutableNester have no
mutable access functions and allow insertion of members only at construction
time. At construction time it checks whether all entered elements are immutable
in the above sense.

As said, I have no idea how much this fits into the general python

2013/11/11  <random832 at fastmail.us>:
>> A built-in function 'isimmutable()' shall tell efficiently whether the
>> object
>> of concern is mutable or not.
> What's the benefit over attempting to hash() the object?
> copy.deepcopy already has special case for int, string, and tuples
> (including tuples that do and do not have mutable members) - could what
> you need be accomplished by overriding __copy__ and __deepcopy__ in your
> custom class to return itself if it is immutable?

More information about the Python-list mailing list