Passing Mutable Objects and Side Effects
00:07 In the last lesson, you learned that a Python function can’t change the value of an argument by reassigning the corresponding parameter to something else. However, Python can mutate the object passed as an argument if the object itself, the object that’s passed as an argument, can itself be mutated.
00:28 So, here’s an example. Let’s define a function that takes a single parameter. And, assuming that there’s a zeroth element to it, we’re going to modify it. Now, of course, this function will cause an error if the parameter we provide it doesn’t have a zeroth element, but we’re only using it for this one example, so we’ll be fine.
Now, a list is mutable, so when I call
f() on my list, it’s going to change element
'foo' to those three hyphens (
'---'). And if I create another function… I’ll call this one
g(). It’s going to act on a dictionary. And again, we will only provide a dictionary to it for the purposes of this example.
02:27 The function can’t modify the object. The object and the calling environment is unaffected by anything we might do to it inside the function. If you pass a mutable object, like a list or a dictionary, it’s like pass-by-reference. Again, you can’t reassign the parameter to something else, but you can modify the object that you get.
02:50 This is an example of something we call side effects. A Python function is said to cause a side effect if it modifies its calling environment—for example, modifying an argument object. Now, because Python allows it, should you do it? Well, if someone using your function knows very clearly that that’s the intent, then it’s fine. In fact, for some functions, the side effect is the primary reason we use it.
03:19 But oftentimes, a side effect is created when the writer of the function doesn’t even realize that it’s happening, and so we try to write functions that have side effects very sparingly, make sure we know what we’re doing, make sure that that’s the intent, and if not, don’t do anything that’s going to reassign a parameter value to anything else.
Become a Member to join the conversation.