Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check immutability [duplicate]

In python, is there any way to check if an object is immutable or mutable?

like isimmutable(a) would return True, if a is immutable, else returns False.

like image 950
rnbguy Avatar asked Jul 26 '13 07:07

rnbguy


People also ask

How do you check if something is immutable in Python?

There are no general tests for immutability. An object is immutable only if none of its methods can mutate the underlying data. the answer says: 1) Keys must not be mutable, unless you have a user-defined class that is hashable but also mutable.

What is an example of immutability?

String is an example of an immutable type. A String object always represents the same string. StringBuilder is an example of a mutable type. It has methods to delete parts of the string, insert or replace characters, etc. Since String is immutable, once created, a String object always has the same value.


2 Answers

There are no general tests for immutability. An object is immutable only if none of its methods can mutate the underlying data.

take a look at this question

the answer says:

1) Keys must not be mutable, unless you have a user-defined class that is hashable but also mutable. That's all that's forced upon you. However, using a hashable, mutable object as a dict key might be a bad idea.

2) By not sharing values between the two dicts. It's OK to share the keys, because they must be immutable. Copying the dictionary, in the copy module sense, is definitely safe. Calling the dict constructor here works, too: b = dict(a). You could also use immutable values.

3) All built-in immutable types are hashable. All built-in mutable types are not hashable. For an object to be hashable, it must have the same hash over its entire lifetime, even if it is mutated.

4) Not that I'm aware of; I'm describing 2.x.

A type 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. User-defined types are always mutable.

An object is mutable if it is not immutable. An object is immutable if it consists, recursively, of only immutable-typed sub-objects. 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

that should answer youre question

like image 179
Serial Avatar answered Oct 06 '22 01:10

Serial


Do you want to check for immutability, or hashability? If you want to check whether something is hashable, hash it:

try:
    hash(thing)
except TypeError:
    print "It's unhashable."
else:
    print "It's hashable."

Hashability is usually what you want. If you want to check whether something is mutable, there's no general test.

like image 24
user2357112 supports Monica Avatar answered Oct 06 '22 00:10

user2357112 supports Monica