Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace Mutable Default Parameters #221

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

pixeeai
Copy link

@pixeeai pixeeai commented Apr 27, 2024

Using mutable values for default arguments is not a safe practice.
Look at the following very simple example code:

def foo(x, y=[]):
    y.append(x)
    print(y)

The function foo doesn't do anything very interesting; it just prints the result of x appended to y. Naively we might expect this to simply print an array containing only x every time foo is called, like this:

>>> foo(1)
[1]
>>> foo(2)
[2]

But that's not what happens!

>>> foo(1)
[1]
>>> foo(2)
[1, 2]

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, and set.

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:

- def foo(x, y=[]):
+ def foo(x, y=None):
+   y = [] if y is None else y
    y.append(x)
    print(y)

Using None is a much safer default. The new code checks if None is passed, and if so uses an empty list for the value of y. This will guarantee consistent and safe behavior between calls.

Powered by: pixeebot (codemod ID: pixee:python/fix-mutable-params)

@CLAassistant
Copy link

CLAassistant commented Apr 27, 2024

CLA assistant check
All committers have signed the CLA.

@pixeeai
Copy link
Author

pixeeai commented Jul 26, 2024

Hi I've signed the cla for our @pixeeai account - However I am not able to sign it for our @pixeebot account, can you manually approve that account?

Co-authored-by: pixeebot[bot] <104101892+pixeebot[bot]@users.noreply.github.com>
@pixeeai
Copy link
Author

pixeeai commented Nov 2, 2024

Any chance you've had the time to review these changes?

If you're not interested implementing them at this time, no worries. I can close the PR and follow up with additional changes in the future. Also, this plugin is free for non-commercial open sourced projects, so feel free to give it an install if you want to see the other recommended PRs.

Thanks,
Zach

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

2 participants