filmov
tv
The Infamous Python 'Glitch' #computerscience #coding #python

Показать описание
default values in Python functions have what seems to be a strange quirk about them, that has cost many developers many hours of work.
The quirk is that modifying a default parameter, that is a mutable object, will modify that default parameter forever. For example, if I have an empty list as a default parameter, and I append to that list in the function, then the NEXT TIME I run that function, the default parameter will be different. Crazy! Find out why this is by watching this short.
Let me tell you my experience with these default values. When I was doing a LeetCode question once, I used a default parameter (if i remember correctly, for memoization). I kept getting different results when I ran the code versus when LeetCode ran my test cases. So I would look at the individual test cases that my code failed on, and I'd take them and run them myself – but they would work when I ran them! The problem was that LeetCode was running the function multiple times in a test, and my function was modifying its default parameters, so it was acting differently each time.
#programming
The quirk is that modifying a default parameter, that is a mutable object, will modify that default parameter forever. For example, if I have an empty list as a default parameter, and I append to that list in the function, then the NEXT TIME I run that function, the default parameter will be different. Crazy! Find out why this is by watching this short.
Let me tell you my experience with these default values. When I was doing a LeetCode question once, I used a default parameter (if i remember correctly, for memoization). I kept getting different results when I ran the code versus when LeetCode ran my test cases. So I would look at the individual test cases that my code failed on, and I'd take them and run them myself – but they would work when I ran them! The problem was that LeetCode was running the function multiple times in a test, and my function was modifying its default parameters, so it was acting differently each time.
#programming