A Nasty Hidden Feature of Python That Many Programmers Aren't Aware Of
...and counterintuitive when you discover it.
Mutability in Python is possibly one of the most misunderstood and overlooked concepts. The above image demonstrates an example that many Python programmers (especially new ones) struggle to understand.
Can you figure it out? If not, let’s understand it.
The default parameters of a function are evaluated right at the time the function is defined. In other words, they are not evaluated each time the function is called (like in C++).
Thus, as soon as a function is defined, the function object stores the default parameters in its
__defaults__ attribute. We can verify this below:
Thus, if you specify a mutable default parameter in a function and mutate it, you unknowingly and unintentionally modify the parameter for all future calls to that function.
This is shown in the demonstration below. Instead of creating a new list at each function call, Python appends the element to the same copy.
So what can we do to avoid this?
Instead of specifying a mutable default parameter in a function’s definition, replace them with
None. If the function does not receive a corresponding value during the function call, create the mutable object inside the function.
This is demonstrated below:
As shown above, we create a new list if the function didn’t receive any value when it was called. This lets you avoid the unexpected behavior of mutating the same object.
Thanks for reading Daily Dose of Data Science! Subscribe for free to learn something new and insightful about Python and Data Science every day.
Find the code for this post here: GitHub.
👉 Read what others are saying about this post on LinkedIn.
👉 Tell me you liked this post by leaving a heart react ❤️.
👉 If you love reading this newsletter, feel free to share it with friends!
I like to explore, experiment and write about data science concepts and tools. You can read my articles on Medium. Also, you can connect with me on LinkedIn and Twitter.