Check for mutability in Python?

后端 未结 7 1737
小鲜肉
小鲜肉 2020-12-28 13:23

Consider this code:

a = {...} # a is an dict with arbitrary contents
b = a.copy()
  1. What role does mutability play in the keys and valu
相关标签:
7条回答
  • 2020-12-28 14:08

    There's really no guarantee that a type which is hashable is also immutable, but at very least, correctly implementing __hash__ requires that the type is immutable, with respect to its own hash, and to equality. This is not enforced in any particular way.

    However, we are all adults. It would be unwise to implement __hash__ unless you really meant it. Roughly speaking, this just boils down to saying that if a type actually can be used as a dictionary key, then it is intended to be used in that way.

    If you're looking for something that is like a dict, but also immutable, then namedtuple might be your best bet from what's in the standard library. Admittedly it's not a very good approximation, but it's a start.

    0 讨论(0)
提交回复
热议问题