On Tue, Nov 12, 2013 at 6:01 PM, Frank-Rene Schäfer <fsch...@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)
-378539185
>>> x=1,2,[3]
>>> hash(x)
Traceback (most recent call last):
  File "<pyshell#424>", line 1, in <module>
    hash(x)
TypeError: unhashable type: 'list'

There's your recursive function!

def isimmutable(x):
    try:
        hash(x)
        return True
    except TypeError:
        return False
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to