Skip to content

Commit 86d6d10

Browse files
author
boraxpr
committedFeb 14, 2020
bites 212 - Use contextlib.suppress to suppress exceptions as opposed to a try/catch method
1 parent b56dc57 commit 86d6d10

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed
 

‎.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -78,3 +78,4 @@
7878
/81/README.md
7979
/234/README.md
8080
/219/README.md
81+
/212/README.md

‎212/summing.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from contextlib import suppress
2+
3+
4+
def sum_numbers(numbers):
5+
"""This generator divides each nummber by its consecutive number.
6+
So if it gets passed in [4, 2, 1] it yields 4/2 and 2/1.
7+
It ignores ZeroDivisionError and TypeError exceptions (latter happens
8+
when a string or other non-numeric data type is in numbers)
9+
10+
Task: use contextlib's suppress twice to make the code below more concise.
11+
"""
12+
for i, j in zip(numbers, numbers[1:]):
13+
# replace the block below
14+
with suppress(TypeError):
15+
with suppress(ZeroDivisionError):
16+
yield i/j

‎212/test_summing.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import inspect
2+
3+
from summing import sum_numbers
4+
5+
6+
def test_functionality():
7+
numbers = [1, 2, 0, 4, 5, 12, 'a', 3]
8+
actual = list(sum_numbers(numbers))
9+
expected = [0.5, 0.0, 0.8, 0.4166666666666667]
10+
assert actual == expected
11+
12+
13+
def test_use_of_idioms():
14+
src = inspect.getsource(sum_numbers)
15+
assert 'try' not in src
16+
assert 'except ' not in src
17+
assert 'yield' in src
18+
assert 'TypeError' in src
19+
assert 'ZeroDivisionError' in src
20+
assert src.count('suppress(') in (1, 2)
21+
assert src.count('with') in (1, 2)

0 commit comments

Comments
 (0)
Please sign in to comment.