The Problem With Mutable Objects: Accidental Modification
Explore the challenges of passing mutable objects to functions in Python and how this can cause unintended modifications. Learn why defensive copying is used to protect data and how adopting immutable objects like tuples provides a safer alternative. This lesson helps you understand the risks of mutability and practical ways to avoid accidental changes in your code.
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:
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 ...