JLLeitschuh / bulk-security-pr-generator

Generate thousands of pull requests to fix widespread security vulnerabilities across GitHub.
MIT License
34 stars 14 forks source link

Replace `dataclass` Mutable Default Values with Call to `field` #12

Closed pixeebot[bot] closed 6 months ago

pixeebot[bot] commented 7 months ago

When defining a Python dataclass it is not safe to use mutable datatypes (such as list, dict, or set) as defaults for the attributes. This is because the defined attribute will be shared by all instances of the dataclass type. Using such a mutable default will ultimately result in a ValueError at runtime. This codemod updates attributes of dataclasses.dataclass with mutable defaults to use dataclasses.field instead. The dataclass documentation providesmore details about why using field(default_factory=...) is the recommended pattern.

Our changes look something like this:

-from dataclasses import dataclass
+from dataclasses import field, dataclass

 @dataclass
 class Person:
     name: str = ""
-    phones: list = []
-    friends: dict = {}
-    family: set = set()
+    phones: list = field(default_factory=list)
+    friends: dict = field(default_factory=dict)
+    family: set = field(default_factory=set)
More reading * [https://docs.python.org/3/library/dataclasses.html#mutable-default-values](https://docs.python.org/3/library/dataclasses.html#mutable-default-values)

Powered by: pixeebot (codemod ID: pixee:python/fix-dataclass-defaults)

pixeebot[bot] commented 6 months ago

I'm confident in this change, but I'm not a maintainer of this project. Do you see any reason not to merge it?

If this change was not helpful, or you have suggestions for improvements, please let me know!

pixeebot[bot] commented 6 months ago

Just a friendly ping to remind you about this change. If there are concerns about it, we'd love to hear about them!

pixeebot[bot] commented 6 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.