Skip to content

Commit

Permalink
use as an example effect and add it in test_readme
Browse files Browse the repository at this point in the history
  • Loading branch information
ebonnal committed Jan 23, 2025
1 parent 286a8cc commit 3ae866b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 11 deletions.
24 changes: 13 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
)

Expand All @@ -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`
Expand Down
15 changes: 15 additions & 0 deletions tests/test_readme.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down

0 comments on commit 3ae866b

Please sign in to comment.