2

Curious about whether we can use hash() to check if an object is mutable or not?

11
  • 1
    What is the problem you're actually trying to solve? Commented Aug 3, 2016 at 18:58
  • 2
    See __hash__. Strictly speaking, it's possible. The requirement is that any properties involved in equality are immutable. Properties not involved in equality could be mutable. This is, however, extremely ill-advised. Why do you need to know if a particular object is mutable? Commented Aug 3, 2016 at 19:01
  • 3
    To what end? Why does it matter to you whether a given thing is mutable? That's not the problem you're trying to solve, that's how you're trying to solve it. Commented Aug 3, 2016 at 19:08
  • 2
    @jonrsharpe I think how to satisfy his curiosity is the problem he wants to solve. Is it reasonable? Commented Aug 3, 2016 at 19:17
  • 2
    @HaochenWu it's not unreasonable, but it's useful to mention, and more or less completely pointless to speculate on. Commented Aug 3, 2016 at 19:26

1 Answer 1

4
>>> from collections.abc import Hashable
>>> mutable = [list, bytearray, set, dict]
>>> immutable = [int, float, complex, str, tuple, frozenset, bytes]
>>> all(isinstance(x(), Hashable) for x in immutable)
True
>>> any(isinstance(x(), Hashable) for x in mutable)
False

all mutable objects are unhashable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.