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 dataclass Mutable Default Values with Call to field #12

Conversation

pixeebot[bot]
Copy link
Contributor

@pixeebot pixeebot bot commented Apr 16, 2024

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

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

Copy link
Contributor Author

pixeebot bot commented Apr 24, 2024

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!

Copy link
Contributor Author

pixeebot bot commented Apr 25, 2024

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

Copy link
Contributor Author

pixeebot bot commented May 1, 2024

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.

@pixeebot pixeebot bot closed this May 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

0 participants