From b243840e4b4980fed84f75bcddf3e5c68e00378a Mon Sep 17 00:00:00 2001 From: Zanie Blue Date: Wed, 11 Oct 2023 16:14:34 -0500 Subject: [PATCH] Add an example of an unsafe fix (#7924) Per review in #7901 adds an example of an unsafe fix. --- docs/configuration.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/docs/configuration.md b/docs/configuration.md index 9a6ea2d0b4d42..6707b8c71c313 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -393,6 +393,36 @@ whether a rule supports fixing, see [_Rules_](rules.md). Ruff labels fixes as "safe" and "unsafe". The meaning and intent of your code will be retained when applying safe fixes, but the meaning could be changed when applying unsafe fixes. +For example, [`unnecessary-iterable-allocation-for-first-element`](../rules/unnecessary-iterable-allocation-for-first-element) (`RUF015`) is a rule which checks for potentially unperformant use of `list(...)[0]`. The fix replaces this pattern with `next(iter(...))` which can result in a drastic speedup: + +```shell +$ python -m timeit "head = list(range(99999999))[0]" +1 loop, best of 5: 1.69 sec per loop +``` + +```shell +$ python -m timeit "head = next(iter(range(99999999)))" +5000000 loops, best of 5: 70.8 nsec per loop +``` + +However, when the collection is empty, this changes the raised exception from an `IndexError` to `StopIteration`: + +```shell +$ python -c 'list(range(0))[0]' +Traceback (most recent call last): + File "", line 1, in +IndexError: list index out of range +``` + +```shell +$ python -c 'next(iter(range(0)))[0]' +Traceback (most recent call last): + File "", line 1, in +StopIteration +``` + +Since this could break error handling, this fix is categorized as unsafe. + Ruff only enables safe fixes by default. Unsafe fixes can be enabled by settings [`unsafe-fixes`](settings.md#unsafe-fixes) in your configuration file or passing the `--unsafe-fixes` flag to `ruff check`: ```shell