2 ms·
> What is unexpected is that the default value assigned to a non-provided argument is not consistent. In my example I show that the parameter "visited" has a de
by isitmadeofglass 4y ago
> What is unexpected is that the default value assigned to a non-provided argument is not consistent. In my example I show that the parameter "visited" has a default value of [] if no argument is passed in.
No you don’t. And calling a mutable value “not consistent” because it’s not immutable is just changing the words used after your mistake of immutable vs mutable. You haven’t done what you think you’ve done because you don’t understand that [] is not “a new empty list every time it is referenced”, but is just a single mutable list. So you’ve provided a default mutable value, which initially is [], but by the nature of being mutable might change in the future. And that is what gets used if there is no value provided. It’s exactly the same behavior as if you define a named variable with an initially empty list, and pass that list to the default. If you want it to be initiated to [] every time no argument is passed, then you need to initiate a new mutable list as the argument on each call. Just like you wouldn’t be able to define a named list once as empty, and expect every call of .append() to give you a new list with only one element.
You’ve passed a single list as the default, not a list imitator, or some crazy “spawns new empty lists on references” object.
And yes, you could have default arguments only support immutable values, then you would not be able to pass in a whole range of objects in defaults.