Skip to content

Commit 8acd52d

Browse files
authored
[pyupgrade] Make fix unsafe if it deletes comments (UP033) (#22871)
1 parent c4811fb commit 8acd52d

3 files changed

Lines changed: 50 additions & 1 deletion

File tree

crates/ruff_linter/resources/test/fixtures/pyupgrade/UP033_0.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,11 @@ def lru_cache(maxsize=None):
4444
@lru_cache(maxsize=None)
4545
def ok():
4646
pass
47+
48+
49+
50+
@functools.lru_cache(
51+
maxsize=None, # text
52+
)
53+
def fixme_unsafe():
54+
pass

crates/ruff_linter/src/rules/pyupgrade/rules/lru_cache_with_maxsize_none.rs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use ruff_diagnostics::Applicability;
12
use ruff_python_ast::{self as ast, Arguments, Decorator, Expr, Keyword};
23
use ruff_text_size::{Ranged, TextRange};
34

@@ -38,6 +39,9 @@ use crate::{AlwaysFixableViolation, Edit, Fix};
3839
/// ## Options
3940
/// - `target-version`
4041
///
42+
/// ## Fix safety
43+
/// This rule's fix is marked as safe, unless the expression contains comments.
44+
///
4145
/// ## References
4246
/// - [Python documentation: `@functools.cache`](https://docs.python.org/3/library/functools.html#functools.cache)
4347
#[derive(ViolationMetadata)]
@@ -103,7 +107,21 @@ pub(crate) fn lru_cache_with_maxsize_none(checker: &Checker, decorator_list: &[D
103107
)?;
104108
let reference_edit =
105109
Edit::range_replacement(binding, decorator.expression.range());
106-
Ok(Fix::safe_edits(import_edit, [reference_edit]))
110+
111+
let applicability = if checker
112+
.comment_ranges()
113+
.intersects(decorator.expression.range())
114+
{
115+
Applicability::Unsafe
116+
} else {
117+
Applicability::Safe
118+
};
119+
120+
Ok(Fix::applicable_edits(
121+
import_edit,
122+
[reference_edit],
123+
applicability,
124+
))
107125
});
108126
}
109127
}

crates/ruff_linter/src/rules/pyupgrade/snapshots/ruff_linter__rules__pyupgrade__tests__UP033_0.py.snap

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,26 @@ help: Rewrite with `@functools.cache
5555
16 | @other_decorator
5656
17 | def fixme():
5757
18 | pass
58+
59+
UP033 [*] Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)`
60+
--> UP033_0.py:50:21
61+
|
62+
50 | @functools.lru_cache(
63+
| _____________________^
64+
51 | | maxsize=None, # text
65+
52 | | )
66+
| |_^
67+
53 | def fixme_unsafe():
68+
54 | pass
69+
|
70+
help: Rewrite with `@functools.cache
71+
47 |
72+
48 |
73+
49 |
74+
- @functools.lru_cache(
75+
- maxsize=None, # text
76+
- )
77+
50 + @functools.cache
78+
51 | def fixme_unsafe():
79+
52 | pass
80+
note: This is an unsafe fix and may change runtime behavior

0 commit comments

Comments
 (0)