0

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()?

Abhishek Bhatia
  • 9,404
  • 26
  • 87
  • 142
  • 4
    No, it will keep the same set. This is a common mistake. Just use `None` as a default and initialize a new empty set if `visited is None`. – L3viathan Dec 21 '18 at 13:24
  • 1
    Do you understand the behaviour in general: https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument If so. why would you expect a recursive call to behave any differently from any other function call? – Chris_Rands Dec 21 '18 at 13:31

1 Answers1

1

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:

iBug
  • 35,554
  • 7
  • 89
  • 134
  • `For example, the following function accumulates the arguments passed to it on subsequent calls:` What function? – nicholishen Dec 21 '18 at 13:35