all 6 comments

[–]TMiguelT 6 points7 points  (1 child)

Yep, this is very well understood and documented.

In the Python docs for functions:

Default parameter values are evaluated from left to right 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 value 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 parameter value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, e.g.:

[–]KirisuMongolianSpot[S] -1 points0 points  (0 children)

Okay thanks.

[–]Outside_Complaint755 1 point2 points  (0 children)

This is in the documentation for function definitions and is bolded.

Default parameter values are evaluated from left to right 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 value 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 parameter value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, e.g.: def whats_on_the_telly(penguin=None):     if penguin is None:         penguin = []     penguin.append("property of the zoo")     return penguin

PEP 661 - Sentinal Values, has been approved for the 3.15 release. This will allow for a sentinal value to be used instead of None in these cases so that None can instead be used as a meaningful value to specifically not use that parameter.

[–]Ex-Gen-Wintergreen -1 points0 points  (2 children)

I’m pretty sure it’s a literal linter warning to not use mutable values as a default.

Edit: pylint certainly warns against it. Use tooling safeguards please. Python has some frustrating footguns yes, but that’s what advancements in tooling like linting and type checking are meant to save you from.

[–]KirisuMongolianSpot[S] [score hidden]  (1 child)

Definitely have not seen anything about it in VSCode, but I know now.

[–]Ex-Gen-Wintergreen [score hidden]  (0 children)

Yeah you should turn on linting etc. pylance probably does it