python function default parameter is evaluated only once? [duplicate]

Python passes parameters to functions by value; So for objects, the value passed is a reference to the object, not a new copy of the object.

That, along with the following part of the official docs is what helped me understand it better (emphasis mine):

Default parameter values are evaluated […] when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. […] A way around this is to use None as the default, and explicitly test for it in the body of the function […]

Putting it all together:

If you define the default for a parameter to be a mutable object (such as []) then the “pre-computed” value is the reference to that object, so each call to the function will always reference the same object, which can then be mutated across multiple invocations of the function.

However, since None is an immutable built-in type, the “pre-computed” value for a default of None is simply that. So the parameter will be None each time you call the function.

Hopefully that helps! I do think that the tutorial could have had better wording, because I was also confused by that at first.

Leave a Comment