The Infamous Python "Glitch"

Publicado em: 09 Março 2024
no canal de: Red Black Tech
807
21

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


Nesta página do site você pode assistir ao vídeo on-line The Infamous Python "Glitch" duração hora minuto segundo em boa qualidade , que foi baixado pelo usuário Red Black Tech 09 Março 2024, compartilhe o link com seus amigos e conhecidos, no youtube este vídeo já foi visto 807 vezes e gostou 21 espectadores. Boa visualização!