diff --git a/README.md b/README.md index c0e3e05..4d78fd7 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ $ refurb file.py folder/ ``` > **Note** -> Refurb must be ran on Python 3.10+, though it can check Python 3.6+ code by setting the `--python-version` flag. +> Refurb must be ran on Python 3.10+, though it can check Python 3.7+ code by setting the `--python-version` flag. ## Explanations For Checks diff --git a/docs/checks.md b/docs/checks.md index a1148a4..c8a1846 100644 --- a/docs/checks.md +++ b/docs/checks.md @@ -2055,7 +2055,7 @@ cmd = shlex.join(args) Categories: `itertools` `performance` `readability` -When flattening an list of lists, use the `chain.from_iterable` function +When flattening a list of lists, use the `chain.from_iterable()` function from the `itertools` stdlib package. This function is faster than native list/generator comprehensions or using `sum()` with a list default. @@ -2083,9 +2083,13 @@ from itertools import chain rows = [[1, 2], [3, 4]] -flat = chain.from_iterable(*rows) +flat = chain.from_iterable(rows) ``` +Note: `chain.from_iterable()` returns an iterator, which means you might +need to wrap it in `list()` depending on your use case. Refurb cannot +detect this (yet), so this is something you will need to keep in mind. + Note: `chain(*x)` may be marginally faster/slower depending on the length of `x`. Since `*` might potentially expand to a lot of arguments, it is better to use `chain.from_iterable()` when you are unsure. diff --git a/refurb/checks/itertools/use_chain_from_iterable.py b/refurb/checks/itertools/use_chain_from_iterable.py index 4961c76..6fb6a5d 100644 --- a/refurb/checks/itertools/use_chain_from_iterable.py +++ b/refurb/checks/itertools/use_chain_from_iterable.py @@ -15,7 +15,7 @@ @dataclass class ErrorInfo(Error): """ - When flattening an list of lists, use the `chain.from_iterable` function + When flattening a list of lists, use the `chain.from_iterable()` function from the `itertools` stdlib package. This function is faster than native list/generator comprehensions or using `sum()` with a list default. @@ -43,9 +43,13 @@ class ErrorInfo(Error): rows = [[1, 2], [3, 4]] - flat = chain.from_iterable(*rows) + flat = chain.from_iterable(rows) ``` + Note: `chain.from_iterable()` returns an iterator, which means you might + need to wrap it in `list()` depending on your use case. Refurb cannot + detect this (yet), so this is something you will need to keep in mind. + Note: `chain(*x)` may be marginally faster/slower depending on the length of `x`. Since `*` might potentially expand to a lot of arguments, it is better to use `chain.from_iterable()` when you are unsure.