Description
Description
Hi there! I've been working on enabling RUF012 (Mutable class variables should not have default values) for OpenLibrary, and I believe the documentation for this rule could be enhanced to make it more actionable and clear. Specifically, I'd like to propose the following improvements:
1. Provide a Suggestion/Example for Immutable Types That Work for dict:
The current documentation for RUF012 highlights the issue of mutable default values in class variables but doesn't provide a concrete example of how to handle dict types immutably. A common solution is to use types.MappingProxyType, which creates an immutable wrapper around a dictionary. Adding an example of this would make the rule more practical and easier to implement.
Example:
from types import MappingProxyType
class MyClass:
# Instead of a mutable dict
MY_DICT: dict[str, str] = {}
# Use an immutable MappingProxyType
MY_DICT: MappingProxyType[str, str] = MappingProxyType({"key": "value"})
2. Provide an Example of Moving a Variable to Be an Instance Variable:
Another way to address mutable class variables is to move them to instance variables initialized in __init__
.
Example:
class MyClass:
# Instead of a mutable class variable
MY_LIST: list[int] = []
# Move it to an instance variable
def __init__(self):
self.my_list: list[int] = []
These additions would make the documentation more comprehensive and actionable, especially for developers who are new to the rule or Python's best practices for immutability.
I hope this is helpful. Unfortunately, I don't have time now to update the docs myself but wanted to at least create an issue for it. Thanks for your time and consideration!
Activity