A builtin is used in a way that does more work than the result needs
What it finds
Builtins used the long way round, doing more work than the result needs:
- sorted(xs)[0] and sorted(xs)[-1] sort everything to find one element, where min(xs) and max(xs) look at each element once; - list(xs)[0] copies an iterable to read its first item, where next(iter(xs)) reads only that; - sum(lists, []) makes a new list for every addition, which takes quadratic time, where itertools.chain.from_iterable or a comprehension does not; - key in d.keys() builds a view to search where key in d asks the dict directly; - any([...]) and all([...]) compute every item of a list comprehension before the test, where a generator stops as soon as the result is known. The fix removes the brackets; it is unsafe, because items after the deciding one are then no longer computed, which matters if computing them has effects.
From the rule's source, wasteful_idiom.rs.
def stats(values, items, lists, mapping, key): low = sorted(values)[0]tx0 reports: sorted(...)[0] sorts everything to find the smallest; min looks once high = sorted(values)[-1]tx0 reports: sorted(...)[-1] sorts everything to find the largest; max looks once first = list(items)[0]tx0 reports: list(...)[0] copies everything to read the first item flat = sum(lists, [])tx0 reports: sum(..., []) copies the list at every step found = key in mapping.keys()tx0 reports: in on .keys() builds a view to search ordered = sorted(values, key=len)[0]tx0 reports: sorted(...)[0] sorts everything backwards = sorted(values, reverse=True)[0] return low, high, first, flat, found, ordered, backwards, sum(values), key in mapping Turn it on, off or suppress it
The rule runs from the strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/python:wasteful-idiom" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
# tx0: ignore[tx0/python:wasteful-idiom] reason="..."tx0 explain tx0/python:wasteful-idiom shows the same in the terminal. Found a false positive? Report it.