On 2013-11-12 11:14, Steven D'Aprano wrote:
On Tue, 12 Nov 2013 18:12:43 +1100, Chris Angelico wrote:

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

I'm afraid that doesn't test for immutability. It tests for hashability,
which is different.

I am going to nitpick below for nitpicking's sake, but I agree with this.

No well-behaved mutable object can be hashable, but that's not to say
that badly-behaved mutable objects won't be hashable.

That's not quite true. A well-behaved mutable may be (well-behaved) hashable as long as the allowed mutations do not affect the equality comparison. For example, in Python 2, all new classes are mutable by default, but they are also well-behaved hashable by default because their equality comparison is identity comparison. None of the mutations affect object identity, so the hash based on identity remains well-behaved.

And every immutable
object should be hashable, but that's not to say that some immutable
objects might choose, for their own reasons, not to be hashable.

I would also dispute this. A tuple itself is immutable, but it may not be hashable because one of its contained objects is unhashable (whether due to mutability or something else).

So your function is subject to both false negatives and false positives.

Agreed.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to