| Start |
|---|
| Mutable vs Immutable There are two kind of types in Python. Immutable types and mutable types. ImmutablesAn object of an immutable type cannot be changed. Any attempt to modify the object will result in a copy being created. This category includes: integers, floats, complex, strings, bytes, tuples, ranges and frozensets. To highlight this property, let's play with the Okay, 1 is not 3... Breaking news... Maybe not. However, this behaviour is often forgotten when it comes to more complex types, especially strings. Aha! See? We can modify it! No. While it seems we can change the string named by the variable In this case it is clear that if we want to retain the first string, we need a copy. But is that so obvious for other types? ExerciseNow, knowing how a immutable types work, what would you say with the below piece of code? Is it wise? MutablesAn object of a mutable type can be changed, and it is changed in-situ. No implicit copies are done. This category includes: lists, dictionaries, bytearrays and sets. Let's continue to play with our little (As a side note, I use bytes containing ascii data to make my point clear, but remember that bytes are not designed to hold textual data. May the force pardon me.) What do we have? We create a bytearray, modify it and using the Of course, if an object is going to be modified often, a mutable type does a much better job than an immutable type. Unfortunately, the reality of this property is often forgotten when it hurts the most. Okay... Waiiit a second... Indeed. ExerciseNow you better understand what side effect is implied by a mutable type, can you explain what is going wrong in this example? |
| Mutable and Immutable as Arguments One of the major use case when a developer needs to take mutability into account is when passing arguments to a function. This is very important, because this will determine the ability for the function to modify objects that doesn't belong to its scope, or in other words if the function has side effects. This is also important to understand where the result of a function has to be made available. Here, the mistake is to think that This doesn't go the same for tuples. At the beginning of the function, ExerciseNote: What do you think of this function? Does it have side effects? Is the return necessary? After the call, what is the value of |
Read Article
https://develop.horje.com/learn/1434/reference