def f(x, lst=[]): when is that default made, and does every call get its own list? Call it repeatedly, watch what it holds. Try the fix with None. An…
Why it matters
This gotcha bites almost every Python beginner, and many old hands. Knowing "defaults are worked out at def time" explains this bug, mutable class attributes, a frozen def f(x=time.time()), and why the None sentinel is everywhere.
The key idea
A default is worked out once, when def runs
Common mistakes
My empty Python list is quietly full when I call again A default is worked out once at def time. A mutable default is shared by every call. Use the None sentinel.
My function treats an empty list passed on purpose as not passedif not nampan is also true for an empty list passed on purpose. Use if nampan is None to tell "not passed" apart.
Every instance of my class shares one list, though I never made it staticclass C: items = [] is shared by every instance for the same reason: that line runs once. Make the list in __init__, not in the class body.
Try it in this playground
With nampan=[], make three orders All three print the same id and the tray fills up: one list for every call.
Switch to None with the is None guard Now every call prints another id, and every tray holds only its own kue.
Use the default nampan_baru() and order twice "nampan baru dibuat" prints once, before "toko buka": the default is worked out at def time.
Switch the container to the book (dict)buku={} is the same trap: a dict is mutable too, made once too.