From 9128955bf9baf5005c6ed372fd927f23a5774d34 Mon Sep 17 00:00:00 2001 From: jxxghp Date: Thu, 14 May 2026 22:18:59 +0800 Subject: [PATCH] fix: preserve scalar items in list flatten Fixes #5705 --- app/utils/structures.py | 6 +++++- tests/test_structures.py | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 tests/test_structures.py diff --git a/app/utils/structures.py b/app/utils/structures.py index 2e2fb651..131cd5a6 100644 --- a/app/utils/structures.py +++ b/app/utils/structures.py @@ -50,7 +50,11 @@ class ListUtils: if not any(isinstance(sublist, list) for sublist in nested_list): return nested_list - return [item for sublist in nested_list if isinstance(sublist, list) for item in sublist] + return [ + item + for sublist in nested_list + for item in (sublist if isinstance(sublist, list) else [sublist]) + ] class SetUtils: diff --git a/tests/test_structures.py b/tests/test_structures.py new file mode 100644 index 00000000..90b87aa4 --- /dev/null +++ b/tests/test_structures.py @@ -0,0 +1,15 @@ +from unittest import TestCase + +from app.utils.structures import ListUtils + + +class ListUtilsTest(TestCase): + def test_flatten_keeps_scalar_items_in_mixed_list(self): + self.assertEqual(ListUtils.flatten([1, [2, 3], 4]), [1, 2, 3, 4]) + + def test_flatten_returns_plain_list_unchanged(self): + source = [1, 2, 3] + self.assertEqual(ListUtils.flatten(source), source) + + def test_flatten_rejects_non_list_input(self): + self.assertEqual(ListUtils.flatten("1,2,3"), [])