mirror of
https://github.com/astral-sh/ruff.git
synced 2025-08-04 10:48:32 +00:00
[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:
parent
08a0995108
commit
9fe89ddfba
1 changed files with 20 additions and 4 deletions
|
@ -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
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue