Before talk about this, let's …
Before talk about this, let's see some definitions.
Mutable Def:
Mutable objects can change their value but keep their id().
Hashable Def:
Objects whose value can change are said to be mutable;
Objects whose value is unchangeable once they are created are called immutable. (The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.)
An object’s mutability is determined by its type; for instance, numbers,
strings and tuples are immutable, while dictionaries, sets and lists are mutable.
We can use hash() to check if an object is hashable.
But there seems no method to check if an object is mutable or not.
Google "python mutable check". Seems many people use hash() to check if an
object is mutable or not...
Python documentation said "All of Python’s immutable built-in objects are
hashable, while no mutable containers (such as lists or dictionaries) are."
So... the questions are:
-
Is there any hashable built-in object is mutable?
-
Is there any un-hashable built-in objects is immutable?
If the answers of the two questions above is "No".
Then,
-
Can we create an user defined type that is hashable but mutable?
-
Can we create an user defined type that is not hashable but immutable?
If the answers of the four questions above is "No".
Does it mean that we can use hash() to check if an object is mutable or not?
Refs:
http://stackoverflow.com/questions/2671376/hashable-immutable
http://docs.python.org/3/reference/datamodel.html#object.hash
http://docs.python.org/3/tutorial/classes.html
http://eli.thegreenplace.net/2012/03/30/python-objects-types-classes-and-instances-a-glossary/
http://stackoverflow.com/questions/4374006/check-for-mutability-in-python
http://stackoverflow.com/questions/4418741/im-able-to-use-a-mutable-object-as-a-dictionary-key-in-python-is-this-not-disa
http://www.velocityreviews.com/forums/t734950-how-to-test-for-atomicity-mutability-hashability.html
Share
Donation
如果覺得這篇文章對你有幫助, 除了留言讓我知道外, 或許也可以考慮請我喝杯咖啡, 不論金額多寡我都會非常感激且能鼓勵我繼續寫出對你有幫助的文章。
If this blog post happens to be helpful to you, besides of leaving a reply, you may consider buy me a cup of coffee to support me. It would help me write more articles helpful to you in the future and I would really appreciate it.
Related Posts
- 用 Python 抓出我在前公司貢獻了多少 GitHub commits
- [Python] Sort dictionary by key or value
- Python 中讓 urllib 使用 cookie 的方法
- Convert HTML string to XML string with Python
- 嘗試在 Python 中做到 Golang fmt 的效果