From 48ce567dd318dabc2746aa644e92d5e03a57056c Mon Sep 17 00:00:00 2001 From: Paul Yang Date: Sun, 17 Mar 2024 14:38:00 -0700 Subject: [PATCH] Add `raw_strings` argument to `mf_pformat_many`. --- metricflow/mf_logging/pretty_print.py | 29 +++++++++++------ .../collection_helpers/test_pretty_print.py | 32 +++++++++++++++++++ 2 files changed, 52 insertions(+), 9 deletions(-) diff --git a/metricflow/mf_logging/pretty_print.py b/metricflow/mf_logging/pretty_print.py index 2f8c1bb001..51dcc02cb0 100644 --- a/metricflow/mf_logging/pretty_print.py +++ b/metricflow/mf_logging/pretty_print.py @@ -424,21 +424,32 @@ def mf_pformat_many( # type: ignore include_object_field_names: bool = True, include_none_object_fields: bool = False, include_empty_object_fields: bool = False, + raw_strings: bool = False, ) -> str: - """Prints many objects in an indented form.""" + """Prints many objects in an indented form. + + If raw_strings is set, and a value of the obj_dict is of type str, then use the value itself, not the + representation of the string. e.g. if value="foo", then "foo" instead of "'foo'". Useful for values that contain + newlines. + """ lines: List[str] = [description] for key, value in obj_dict.items(): + if raw_strings and isinstance(value, str): + value_str = value + else: + value_str = mf_pformat( + obj=value, + max_line_length=max(0, max_line_length - len(indent_prefix)), + indent_prefix=indent_prefix, + include_object_field_names=include_object_field_names, + include_none_object_fields=include_none_object_fields, + include_empty_object_fields=include_empty_object_fields, + ) + item_block_lines = ( f"{key}:", indent( - mf_pformat( - obj=value, - max_line_length=max(0, max_line_length - len(indent_prefix)), - indent_prefix=indent_prefix, - include_object_field_names=include_object_field_names, - include_none_object_fields=include_none_object_fields, - include_empty_object_fields=include_empty_object_fields, - ), + value_str, indent_prefix=indent_prefix, ), ) diff --git a/metricflow/test/collection_helpers/test_pretty_print.py b/metricflow/test/collection_helpers/test_pretty_print.py index 63c7de7edb..e20f4b4842 100644 --- a/metricflow/test/collection_helpers/test_pretty_print.py +++ b/metricflow/test/collection_helpers/test_pretty_print.py @@ -148,3 +148,35 @@ def test_pformat_many() -> None: # noqa: D ).rstrip() == result ) + + +def test_pformat_many_with_raw_strings() -> None: # noqa: D + result = mf_pformat_many("Example description:", obj_dict={"object_0": "foo\nbar"}, raw_strings=True) + + assert ( + textwrap.dedent( + """\ + Example description: + + object_0: + foo + bar + """ + ).rstrip() + == result + ) + + +def test_pformat_many_with_strings() -> None: # noqa: D + result = mf_pformat_many("Example description:", obj_dict={"object_0": "foo\nbar"}) + assert ( + textwrap.dedent( + """\ + Example description: + + object_0: + 'foo\\nbar' + """ + ).rstrip() + == result + )