Open
Conversation
Author
|
I'm confident in this change, and the CI checks pass, too! If you see any reason not to merge this, or you have suggestions for improvements, please let me know! |
Author
|
Just a friendly ping to remind you about this change. If there are concerns about it, we'd love to hear about them! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
foodoesn't do anything very interesting; it just prints the result ofxappended toy. Naively we might expect this to simply print an array containing onlyxevery timefoois called, like this:But that's not what happens!
The value of
yis 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
Noneis a much safer default. The new code checks ifNoneis passed, and if so uses an emptylistfor the value ofy. This will guarantee consistent and safe behavior between calls.Powered by: pixeebot (codemod ID: pixee:python/fix-mutable-params)