'isimmutable' and 'ImmutableNester'

Chris Angelico rosuav at gmail.com
Tue Nov 12 08:12:43 CET 2013

On Tue, Nov 12, 2013 at 6:01 PM, Frank-Rene Schäfer <fschaef at gmail.com> wrote:
> A tuple is immutable but it may contain mutable objects. In larger
> hierarchies of objects it may become less obvious whether down
> the lines, there is some mutable object somewhere in the data tree.
> One can define a recursive function to check for immutability
> manually. However first, it may not be as efficient as if it was
> built-in. Second, the existence of a built-in function 'isimmutable'
> puts the concept of immutability some more into the spotlight.
> You might indeed implement some personal 'policy for copy/deepcopy'.
> But, how can you prevent the insertion of an object into the data
> tree which does not follow your copy/deepcopy convention? As soon
> as you allow members of type 'tuple' you must either check recursively
> or only allow ints and strings as tuple members.

>>> x=1,2,3
>>> hash(x)
>>> x=1,2,[3]
>>> hash(x)
Traceback (most recent call last):
  File "<pyshell#424>", line 1, in <module>
TypeError: unhashable type: 'list'

There's your recursive function!

def isimmutable(x):
        return True
    except TypeError:
        return False

More information about the Python-list mailing list