[refurb] Document why UserDict, UserList, UserString are preferred over dict, list, str (FURB189) (#16927)

## Summary

This PR addresses docs issue
https://github.com/astral-sh/ruff/issues/14328.
This commit is contained in:
Daniel Wilton 2025-03-23 17:24:39 +00:00 committed by GitHub
parent 08a0995108
commit 9fe89ddfba
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -9,21 +9,37 @@ use crate::{checkers::ast::Checker, importer::ImportRequest};
/// Checks for subclasses of `dict`, `list` or `str`.
///
/// ## Why is this bad?
/// Subclassing `dict`, `list`, or `str` objects can be error prone, use the
/// `UserDict`, `UserList`, and `UserString` objects from the `collections` module
/// Built-in types don't consistently use their own dunder methods. For example,
/// `dict.__init__` and `dict.update()` bypass `__setitem__`, making inheritance unreliable.
///
/// Use the `UserDict`, `UserList`, and `UserString` objects from the `collections` module
/// instead.
///
/// ## Example
///
/// ```python
/// class CaseInsensitiveDict(dict): ...
/// class UppercaseDict(dict):
/// def __setitem__(self, key, value):
/// super().__setitem__(key.upper(), value)
///
///
/// d = UppercaseDict({"a": 1, "b": 2}) # Bypasses __setitem__
/// print(d) # {'a': 1, 'b': 2}
/// ```
///
/// Use instead:
///
/// ```python
/// from collections import UserDict
///
///
/// class CaseInsensitiveDict(UserDict): ...
/// class UppercaseDict(UserDict):
/// def __setitem__(self, key, value):
/// super().__setitem__(key.upper(), value)
///
///
/// d = UppercaseDict({"a": 1, "b": 2}) # Uses __setitem__
/// print(d) # {'A': 1, 'B': 2}
/// ```
///
/// ## Fix safety