Python·100 questions

Why is it dangerous to write def f(x, arr=[])?

Answer
Default value is computed once at function definition.
List will be shared across calls.
Correct: def f(x, arr=None): arr = arr or [].
Same for dict/set.
Classic Python trap.
Was this answer helpful?

More questions in this topic

Related questions from other topics