Mutable Default Arguments
As we continue our look at places outside of a Boolean context where we can use the
or operator, we’re now going to take a look at how the
or operator can help us when we’re trying to write a function whose intent is to modify the argument value it’s given while at the same time providing a default value for that argument.
Here’s an illustrative example, perhaps not practical, but we’re just trying to get a sense for what the problem is and what the solution is. So, the intent of this
mutable_default() is to append
1 to the end of the list that it’s provided, and if we’re not provided a list at all, create a new list and have
1 added to it.
And we can see that it’s printed out that list, but more importantly, also that list has been changed. Now, if I call
mutable_default() without a parameter, we should expect a new list to be created with
1 appended to it.
What’s happened is that same default parameter value—when we look at it here—this name
lst was created when I imported this function, and so every time we call this without a parameter, it’s going back and grabbing this list that was already created.
So when the
or encounters the left operand to be
False, we use the right operand, which gives us an empty list. So each time we call this with an empty set of parentheses to use the default value,
lst is assigned to
False, and so then we reassign it to be an empty list.
Now, there’s still a catch, and this is a possibility that perhaps using the
or might not be the best solution. I mentioned that before. So, suppose that I create a new list, but I don’t have anything in it yet, and so I want to call
my_new_list. Well, it looks like things worked but, in fact, they didn’t.
my_new_list wasn’t changed, and the reason it wasn’t changed was because
lst had the parameter
my_new_list was empty, and so this evaluated to be
False, and so a new empty list was created.
In fact, you’re probably not going to be able to use an
or statement at all. You want to explicitly check to see if the list is an empty list or if it’s
None, because if it’s
None, then you know a parameter wasn’t provided, but if it’s not
None, then it’s a meaningful list that you can append to.
So, as mentioned before, sometimes
or isn’t the best way to implement the solution to a problem but in many situations it can be and it’s important to know, if you’re going to use it, how to use it correctly.
Become a Member to join the conversation.