...
/The Problem With Mutable Objects: Accidental Modification
The Problem With Mutable Objects: Accidental Modification
Let’s look at the problem of passing mutable objects to a function and learn how we can solve it.
We'll cover the following...
Passing mutable objects to functions
The basic problem with mutable objects is this: if you pass a mutable object into a function, you have no way of guaranteeing that the function won’t change the object. For example:
def evil_func(x):x[0] = 0k = [1, 2, 3]evil_func(k)print(k) # [0, 2, 3]
When you pass k
into evil_func
, the local variable, x
, is given a reference to the same list that is stored in k
. If the function does something to the list in x
, it is actually doing it to the list in k
. When you pass a list into evil_func
, you have no control over what happens to that list.
So, in the example above, even though you might think you are just passing k
into the function, k
actually gets changed by the call!
Sometimes, of course, you might actually want a function to ...