Ludy87 / pyxplora_api

Unofficial python library for the Xplora® API
MIT License
6 stars 2 forks source link

Replace Mutable Default Parameters #169

Closed pixeebot[bot] closed 3 months ago

pixeebot[bot] commented 5 months ago

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.

I have additional improvements ready for this repo! If you want to see them, leave the comment:

@pixeebot next

... and I will open a new PR right away!

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

pixeebot[bot] commented 4 months ago

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!

pixeebot[bot] commented 4 months ago

This change may not be a priority right now, so I'll close it. If there was something I could have done better, please let me know!

You can also customize me to make sure I'm working with you in the way you want.