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
Auf dieser Seite können Sie das Online-Video The Infamous Python "Glitch" mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Red Black Tech 09 März 2024 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 807 Mal angesehen und es wurde von 21 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!