Format python objects of basic built-in type in a pretty way so we could copy-past them to code editor easily. Currently, this support int, float, str, list, tuple, and dict. It also works with `torch.Tensor` via calling `format_tesnor`.
(obj, indent=0, mode="", cache=None, prefix="")
| 3979 | |
| 3980 | |
| 3981 | def _format_py_obj(obj, indent=0, mode="", cache=None, prefix=""): |
| 3982 | """Format python objects of basic built-in type in a pretty way so we could copy-past them to code editor easily. |
| 3983 | |
| 3984 | Currently, this support int, float, str, list, tuple, and dict. |
| 3985 | |
| 3986 | It also works with `torch.Tensor` via calling `format_tesnor`. |
| 3987 | """ |
| 3988 | |
| 3989 | if cache is None: |
| 3990 | cache = {} |
| 3991 | else: |
| 3992 | if (id(obj), indent, mode, prefix) in cache: |
| 3993 | return cache[(id(obj), indent, mode, prefix)] |
| 3994 | |
| 3995 | # special format method for `torch.Tensor` |
| 3996 | if str(obj.__class__) == "<class 'torch.Tensor'>": |
| 3997 | return _format_tensor(obj) |
| 3998 | |
| 3999 | elif obj.__class__.__name__ == "str": |
| 4000 | quoted_string = _quote_string(obj) |
| 4001 | # we don't want the newline being interpreted |
| 4002 | quoted_string = quoted_string.replace("\n", r"\n") |
| 4003 | output = quoted_string |
| 4004 | |
| 4005 | elif obj.__class__.__name__ in ["int", "float"]: |
| 4006 | # for float like `1/3`, we will get `0.3333333333333333` |
| 4007 | output = str(obj) |
| 4008 | |
| 4009 | elif obj.__class__.__name__ in ["list", "tuple", "dict"]: |
| 4010 | parenthesis = { |
| 4011 | "list": "[]", |
| 4012 | "tuple": "()", |
| 4013 | "dict": "{}", |
| 4014 | } |
| 4015 | p1, p2 = parenthesis[obj.__class__.__name__] |
| 4016 | |
| 4017 | elements_without_indent = [] |
| 4018 | if isinstance(obj, dict): |
| 4019 | for idx, (k, v) in enumerate(obj.items()): |
| 4020 | last_element = idx == len(obj) - 1 |
| 4021 | ok = _format_py_obj(k, indent=indent + 1, mode="one-line", cache=cache) |
| 4022 | ov = _format_py_obj( |
| 4023 | v, |
| 4024 | indent=indent + 1, |
| 4025 | mode=mode, |
| 4026 | cache=cache, |
| 4027 | prefix=ok.lstrip() + ": " + "," if not last_element else "", |
| 4028 | ) |
| 4029 | # Each element could be multiple-line, but the indent of its first line is removed |
| 4030 | elements_without_indent.append(f"{ok.lstrip()}: {ov.lstrip()}") |
| 4031 | |
| 4032 | else: |
| 4033 | for idx, x in enumerate(obj): |
| 4034 | last_element = idx == len(obj) - 1 |
| 4035 | o = _format_py_obj( |
| 4036 | x, indent=indent + 1, mode=mode, cache=cache, prefix="," if not last_element else "" |
| 4037 | ) |
| 4038 | # Each element could be multiple-line, but the indent of its first line is removed |
no test coverage detected