I\'m confused on what an immutable type is. I know the float
object is considered to be immutable, with this type of example from my book:
class
The goal of this answer is to create a single place to find all the good ideas about how to tell if you are dealing with mutating/nonmutating (immutable/mutable), and where possible, what to do about it? There are times when mutation is undesirable and python's behavior in this regard can feel counter-intuitive to coders coming into it from other languages.
As per a useful post by @mina-gabriel:
Analyzing the above and combining w/ a post by @arrakëën:
What cannot change unexpectedly?
What can?
by "unexpectedly" I mean that programmers from other languages might not expect this behavior (with the exception or Ruby, and maybe a few other "Python like" languages).
Adding to this discussion:
This behavior is an advantage when it prevents you from accidentally populating your code with mutliple copies of memory-eating large data structures. But when this is undesirable, how do we get around it?
With lists, the simple solution is to build a new one like so:
list2 = list(list1)
with other structures ... the solution can be trickier. One way is to loop through the elements and add them to a new empty data structure (of the same type).
functions can mutate the original when you pass in mutable structures. How to tell?
Non-standard Approaches (in case helpful): Found this on github published under an MIT license:
For custom classes, @semicolon suggests checking if there is a __hash__
function because mutable objects should generally not have a __hash__()
function.
This is all I have amassed on this topic for now. Other ideas, corrections, etc. are welcome. Thanks.