From 3ae866bd9af63acf283a70d79b09d2ed158ee3c5 Mon Sep 17 00:00:00 2001 From: ebonnal Date: Thu, 23 Jan 2025 00:05:15 +0000 Subject: [PATCH] use as an example effect and add it in test_readme --- README.md | 24 +++++++++++++----------- tests/test_readme.py | 15 +++++++++++++++ 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 3e0378e..e7894db 100644 --- a/README.md +++ b/README.md @@ -361,7 +361,7 @@ from requests.exceptions import ConnectionError status_codes_ignoring_resolution_errors: Stream[int] = ( Stream(["https://github.com", "https://foo.bar", "https://github.com/foo/bar"]) .map(requests.get, concurrency=2) - .catch(ConnectionError, when=lambda exception: "Max retries exceeded with url" in str(exception)) + .catch(ConnectionError, when=lambda error: "Max retries exceeded with url" in str(error)) .map(lambda response: response.status_code) ) @@ -371,21 +371,23 @@ assert list(status_codes_ignoring_resolution_errors) == [200, 404] > It has an optional `finally_raise: bool` parameter to raise the first catched exception when iteration ends. > [!TIP] -> You can add side effects for exception handling by passing a `when` function that incorporates the side effect and always returns `True`: +> To apply side effects when catching an exception, integrate them into `when`: ```python -def side_effect(e): - print("Uh-oh!") +errors: List[Exception] = [] + +def store_error(error: Exception) -> bool: + errors.append(error) return True -even_numbers: Stream[float] = ( - Stream(["1", 1, 2, "3", 5] - .map(lambda n: n % 2 == 0) - .catch(TypeError, when=side_effect) -)" +integers_in_string: Stream[int] = ( + Stream("012345foo6789") + .map(int) + .catch(ValueError, when=store_error) +) -# prints Uh-oh twice -even_number() +assert list(integers_in_string) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +assert len(errors) == len("foo") ``` ## `.truncate` diff --git a/tests/test_readme.py b/tests/test_readme.py index d7c09ee..b3cacd6 100644 --- a/tests/test_readme.py +++ b/tests/test_readme.py @@ -199,6 +199,21 @@ def test_catch_example(self) -> None: assert list(status_codes_ignoring_resolution_errors) == [200, 404] + errors: List[Exception] = [] + + def store_error(error: Exception) -> bool: + errors.append(error) + return True + + integers_in_string: Stream[int] = ( + Stream("012345foo6789") + .map(int) + .catch(ValueError, when=store_error) + ) + + assert list(integers_in_string) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + assert len(errors) == len("foo") + def test_truncate_example(self) -> None: five_first_integers: Stream[int] = integers.truncate(5)