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 ...