mirror of
https://github.com/astral-sh/ruff.git
synced 2025-09-29 13:25:17 +00:00

## Summary Fixes #10463 Add `FURB192` which detects violations like this: ```python # Bad a = sorted(l)[0] # Good a = min(l) ``` There is a caveat that @Skylion007 has pointed out, which is that violations with `reverse=True` technically aren't compatible with this change, in the edge case where the unstable behavior is intended. For example: ```python from operator import itemgetter data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)] min(data, key=itemgetter(0)) # ('blue', 1) sorted(data, key=itemgetter(0))[0] # ('blue', 1) sorted(data, key=itemgetter(0), reverse=True)[-1] # ('blue, 2') ``` This seems like a rare edge case, but I can make the `reverse=True` fixes unsafe if that's best. ## Test Plan This is unit tested. ## References https://github.com/dosisod/refurb/pull/333/files --------- Co-authored-by: Charlie Marsh <charlie.r.marsh@gmail.com>
48 lines
486 B
Python
48 lines
486 B
Python
# Errors
|
|
|
|
sorted(l)[0]
|
|
|
|
sorted(l)[-1]
|
|
|
|
sorted(l, reverse=False)[-1]
|
|
|
|
sorted(l, key=lambda x: x)[0]
|
|
|
|
sorted(l, key=key_fn)[0]
|
|
|
|
sorted([1, 2, 3])[0]
|
|
|
|
# Unsafe
|
|
|
|
sorted(l, key=key_fn, reverse=True)[-1]
|
|
|
|
sorted(l, reverse=True)[0]
|
|
|
|
sorted(l, reverse=True)[-1]
|
|
|
|
# Non-errors
|
|
|
|
sorted(l, reverse=foo())[0]
|
|
|
|
sorted(l)[1]
|
|
|
|
sorted(get_list())[1]
|
|
|
|
sorted()[0]
|
|
|
|
sorted(l)[1]
|
|
|
|
sorted(l)[-2]
|
|
|
|
b = True
|
|
|
|
sorted(l, reverse=b)[0]
|
|
|
|
sorted(l, invalid_kwarg=True)[0]
|
|
|
|
|
|
def sorted():
|
|
pass
|
|
|
|
|
|
sorted(l)[0]
|