a guest Oct 21st, 2019 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
- Interview question: **What function can you use to show that a certain data type is mutable?**
- The given answer is: **The id function can be used to check if a given variable is mutable or not.**
- ... How? The [id](https://docs.python.org/3/library/functions.html#id) function basically returns the memory address of the object, so, how can we tell whether an object is mutable or not by using id()?
- Let's define immutability.
- > An object with a fixed value. Immutable objects include numbers, strings and tuples. Such an object cannot be altered. A new object has to be created if a different value has to be stored. They play an important role in places where a constant hash value is needed, for example as a key in a dictionary.
- ### Builtin objects.
- **Mutable**: list, dict ...
- **Immutable**: int, float, str, tuple...
- Only immutable objects can be used as dictionaries keys, in order to compare the keys, the objects are hashed and compared, could we say that hashable objects are inmutable?
- Most of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not; immutable containers (such as tuples and frozensets) are only hashable if their elements are hashable. Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except with themselves), and their hash value is derived from their id().
- Looks like yes, hashable objects are immutable but...
- [Python data model](https://docs.python.org/3/reference/datamodel.html#objects-values-and-types)
- > The value of some objects can change. 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 and lists are mutable.**
- So, a given object is inmutable if it can be hashed. Well, it is not always true. You can still have a user defined class that is hashable and mutable by modifying `__hash__ and __eq__`
- **Proposed answe**r: 'You can usually use the function hash() to check an object mutability, if it is
- hashable it is immutable, although this does not always work as intended as user defined objects might be mutable and hashable'
RAW Paste Data