T
0

TIL the hard way that Python's default arguments are evaluated once, not every call

I spent 3 hours debugging why my list kept growing every time I ran the function, and it turned out the empty list I passed as a default arg was the same object all along, found it buried in a StackOverflow answer from 2011, has anyone else tripped on this one?
1 comments

Log in to join the discussion

Log In
1 Comment
hollyg59
hollyg594d ago
The mutable default argument got me too, but I fixed it by just putting the default inside the function body instead. So instead of writing `def foo(items=[])`, I write `def foo(items=None)` and then set `items = [] if items is None else items` as the first line. That way you get a fresh list every call and it only takes a minute to change. It's annoying that Python works this way, but once you know it, you kind of see it everywhere. I also started adding that pattern to any function that takes a list or dict, even if I'm pretty sure it won't bite me. Saved my butt more than once since then.
6