Skip to content

Commit

Permalink
fix(iterating/flatten)
Browse files Browse the repository at this point in the history
  • Loading branch information
PaulRenvoise committed Jun 3, 2024
1 parent d1ced44 commit 8a69040
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
5 changes: 2 additions & 3 deletions flashback/iterating/flatten.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
from __future__ import annotations

from collections.abc import Iterable
from typing import TypeVar

T = TypeVar("T")


def flatten(iterable: Iterable[T]) -> tuple[T, ...]:
def flatten(iterable: list[T] | tuple[T, ...] | set[T] | frozenset[T] | range) -> tuple[T, ...]:
"""
Unpacks nested iterables into the root `iterable`.
Expand All @@ -33,7 +32,7 @@ def flatten(iterable: Iterable[T]) -> tuple[T, ...]:
"""
items = []
for item in iterable:
if isinstance(item, Iterable) and not isinstance(item, str):
if isinstance(item, (list, tuple, set, frozenset, range)): # noqa: UP038
for nested_item in flatten(item):
items.append(nested_item) # noqa: PERF402
else:
Expand Down
5 changes: 5 additions & 0 deletions tests/iterating/test_flatten.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,8 @@ def test_mixed_types(self):
flattened = flatten([1, (2,), {3, 4}, range(5, 6)])

assert flattened == (1, 2, 3, 4, 5)

def test_nested_dicts(self):
flattened = flatten([[{"key1": 1}], [{"key2": 2}, {"key3": 3}]])

assert flattened == ({"key1": 1}, {"key2": 2}, {"key3": 3})

0 comments on commit 8a69040

Please sign in to comment.