Last active
February 5, 2021 12:31
-
-
Save gidgid/e254befdeae2b34b7c4dbc83c0542ba5 to your computer and use it in GitHub Desktop.
shows how we can use always_iterable to write less code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import reduce | |
from operator import add | |
import pytest | |
from more_itertools import always_iterable | |
def safer_sum(inputs) -> int: | |
iterable_inputs = always_iterable(inputs) # 1 | |
return reduce(add, iterable_inputs, 0) # 1 | |
@pytest.mark.parametrize( | |
"sum_input,expected_sum", | |
[ | |
([1, 2, 3], 6), # 2 | |
([], 0), # 2 | |
(42, 42), # 3 | |
(None, 0), # 4 | |
], | |
) | |
def test_safer_sum_works_with_lists(sum_input, expected_sum): | |
assert safer_sum(sum_input) == expected_sum # 5 | |
def safer_but_complex_sum(inputs) -> int: # 6 | |
if inputs is None: | |
inputs = [] | |
if not isinstance(inputs, list): | |
inputs = [inputs] | |
return reduce(add, inputs, 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment