From 7f63e06dc301414ddc3fe621b8a6bd8a3cd85311 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Ma=C5=9Blanka?= <piotr.maslanka@henrietta.com.pl> Date: Fri, 19 Jun 2020 19:39:51 +0200 Subject: [PATCH] fix stringify --- CHANGELOG.md | 1 + satella/__init__.py | 2 +- satella/coding/transforms/__init__.py | 9 ++++++++- tests/test_coding/test_transforms.py | 3 +++ 4 files changed, 13 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bda02f79..3628e62b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,4 @@ # v2.8.6 * added `time_us` +* updated `stringify` to correctly handle None-cases diff --git a/satella/__init__.py b/satella/__init__.py index e2f4d6cc..0934f03c 100644 --- a/satella/__init__.py +++ b/satella/__init__.py @@ -1 +1 @@ -__version__ = '2.8.6_a2' +__version__ = '2.8.6_a3' diff --git a/satella/coding/transforms/__init__.py b/satella/coding/transforms/__init__.py index dcf65cf2..e1a099e5 100644 --- a/satella/coding/transforms/__init__.py +++ b/satella/coding/transforms/__init__.py @@ -5,7 +5,8 @@ __all__ = ['stringify'] def stringify(obj: tp.Union[tp.Any], stringifier: tp.Callable[[tp.Any], str] = str, - recursively: bool = False) -> tp.Dict[str, str]: + recursively: bool = False, + str_none: bool = False) -> tp.Dict[str, str]: """ Stringify all object: @@ -19,6 +20,7 @@ def stringify(obj: tp.Union[tp.Any], stringifier: tp.Callable[[tp.Any], str] = s :param obj: a list or a dict :param stringifier: function that accepts any arguments and returns a string representation :param recursively: whether to recursively stringify elements, ie. stringify will be called on all the children + :param str_none: whether to return None if given a None. If True, "None" will be returned instead :return: stringified object """ if isinstance(obj, collections.abc.Mapping): @@ -27,5 +29,10 @@ def stringify(obj: tp.Union[tp.Any], stringifier: tp.Callable[[tp.Any], str] = s elif isinstance(obj, collections.abc.Sequence): make_str = (lambda obj2: stringify(obj2, stringifier, True)) if recursively else stringifier return [make_str(v) for v in obj] + elif obj is None: + if str_none: + return stringifier(None) + else: + return None else: return stringifier(obj) diff --git a/tests/test_coding/test_transforms.py b/tests/test_coding/test_transforms.py index 5a94cab8..28fa5c14 100644 --- a/tests/test_coding/test_transforms.py +++ b/tests/test_coding/test_transforms.py @@ -16,3 +16,6 @@ class MyTestCase(unittest.TestCase): dct2 = {1: [1, 2, 3]} self.assertEqual(stringify(dct2, recursively=True), {'1': ['1', '2', '3']}) + + self.assertIsNone(stringify(None)) + self.assertEqual(stringify(None, str_none=True), str(None)) -- GitLab