diff --git a/src/coola/utils/format.py b/src/coola/utils/format.py index 5f0c3c70..9bca96b0 100644 --- a/src/coola/utils/format.py +++ b/src/coola/utils/format.py @@ -7,6 +7,7 @@ "find_best_byte_unit", "repr_indent", "repr_mapping", + "repr_mapping_line", "repr_sequence", "str_human_byte_size", "str_indent", @@ -100,6 +101,37 @@ def repr_mapping(mapping: Mapping, sorted_keys: bool = False, num_spaces: int = return "\n".join(lines) +def repr_mapping_line(mapping: Mapping, sorted_keys: bool = False, separator: str = ", ") -> str: + r"""Compute a single line string representation of the given mapping. + + This function is designed for flat dictionary. If you have a + nested dictionary, you may consider other functions. Note that + this function works for nested dict but the output may not be + nice. + + Args: + mapping: The mapping. + sorted_keys: If ``True``, the keys in the mapping are sorted + before to compute the string representation. + separator: The separator to use between each key-value pair. + + Returns: + The string representation of the mapping. + + Example usage: + + ```pycon + + >>> from coola.utils.format import repr_mapping_line + >>> repr_mapping_line({"key1": "abc", "key2": "meow", "key3": 42}) + key1='abc', key2='meow', key3=42 + + ``` + """ + mapping = sorted(mapping.items()) if sorted_keys else mapping.items() + return separator.join(f"{key}={value!r}" for key, value in mapping) + + def repr_sequence(sequence: Sequence, num_spaces: int = 2) -> str: r"""Compute a string representation of a sequence. diff --git a/tests/unit/utils/test_format.py b/tests/unit/utils/test_format.py index ae63682a..b26a2575 100644 --- a/tests/unit/utils/test_format.py +++ b/tests/unit/utils/test_format.py @@ -6,6 +6,7 @@ find_best_byte_unit, repr_indent, repr_mapping, + repr_mapping_line, repr_sequence, str_human_byte_size, str_indent, @@ -77,6 +78,34 @@ def test_repr_mapping_sorted_keys_false() -> None: assert repr_mapping({"key2": "value2", "key1": "value1"}) == "(key2): value2\n(key1): value1" +####################################### +# Tests for repr_mapping_line # +####################################### + + +def test_repr_mapping_line_empty() -> None: + assert repr_mapping_line({}) == "" + + +def test_repr_mapping_line_1_item() -> None: + assert repr_mapping_line({"key": "value"}) == "key='value'" + + +def test_repr_mapping_line_2_items() -> None: + assert repr_mapping_line({"key1": "value1", "key2": "value2"}) == "key1='value1', key2='value2'" + + +def test_repr_mapping_line_sorted_keys_true() -> None: + assert ( + repr_mapping_line({"key2": "value2", "key1": "value1"}, sorted_keys=True) + == "key1='value1', key2='value2'" + ) + + +def test_repr_mapping_line_sorted_keys_false() -> None: + assert repr_mapping_line({"key2": "value2", "key1": "value1"}) == "key2='value2', key1='value1'" + + ################################### # Tests for repr_sequence # ###################################