The most common use of this is caching and memoization: having a property cached or not doesn't logically change the object, and usually has no effect on equality. Why? The property we're changing has no effect on equality: the hash is unchanged, and example(1) is always equal to example(1), ignoring any other properties. Yet, we're using it as a key of a hash without any trouble. Here, example is not immutable we're modifying it with a.data = 2. What matters is comparison and hashing: the object must always remain equal to itself. Immutability is not actually relevant to dicts it's perfectly fine to use mutable values as keys. strings and tuples), and so are effectively immutable, but it's purely conceptual there's no property at the language level indicating this, neither to your code nor to Python itself. Some objects provide no way to change them (eg. There isn't actually any such thing as mutability or immutability at the language level in Python. Thus, a tuple of lists is mutable you cannot replace the elements of the tuple, but you can modify them through the list interface, changing the overall data. ![]() An object is immutable if it consists, recursively, of only immutable-typed sub-objects. User-defined types are always mutable.Īn object is mutable if it is not immutable. A type is immutable if it is a built-in immutable type: str, int, long, bool, float, tuple, and probably a couple others I'm forgetting. For an object to be hashable, it must have the same hash over its entire lifetime, even if it is mutated.Ĥ) Not that I'm aware of I'm describing 2.x.Ī type is mutable if it is not immutable. All built-in mutable types are not hashable. You could also use immutable values.ģ) All built-in immutable types are hashable. Calling the dict constructor here works, too: b = dict(a). ![]() Copying the dictionary, in the copy module sense, is definitely safe. It's OK to share the keys, because they must be immutable. However, using a hashable, mutable object as a dict key might be a bad idea.Ģ) By not sharing values between the two dicts. ![]() 1) Keys must not be mutable, unless you have a user-defined class that is hashable but also mutable.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |