Let's say you have the function: def f(..., visited= set())
.
Inside, you call f()
again.
In this recursive call, if you don't pass visited, will create a new visited set()?
Let's say you have the function: def f(..., visited= set())
.
Inside, you call f()
again.
In this recursive call, if you don't pass visited, will create a new visited set()?
No. The default argument is processed only once when the def
statement is first run. So if you don't pass another argument for visited
, the same set gets reused and can often lead to unexpected results.
From the Python documentation:
The default values are evaluated at the point of function definition in the defining scope, so that ...
as well as the Important warning below.
The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls: