Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Using mutable values for default arguments is not a safe practice.
Look at the following very simple example code:
The function
foo
doesn't do anything very interesting; it just prints the result ofx
appended toy
. Naively we might expect this to simply print an array containing onlyx
every timefoo
is called, like this:But that's not what happens!
The value of
y
is preserved between calls! This might seem surprising, and it is. It's due to the way that scope works for function arguments in Python.The result is that any default argument value will be preserved between function calls. This is problematic for mutable types, including things like
list
,dict
, andset
.Relying on this behavior is unpredictable and generally considered to be unsafe. Most of us who write code like this were not anticipating the surprising behavior, so it's best to fix it.
Our codemod makes an update that looks like this:
Using
None
is a much safer default. The new code checks ifNone
is passed, and if so uses an emptylist
for the value ofy
. This will guarantee consistent and safe behavior between calls.More reading
I have additional improvements ready for this repo! If you want to see them, leave the comment:
... and I will open a new PR right away!
Powered by: pixeebot (codemod ID: pixee:python/fix-mutable-params)