dump into json, including only basic types, list types and dict types. If other types are included, they will be converted into string.
(obj, max_depth=5, compress=False)
| 16 | |
| 17 | |
| 18 | def serialize(obj, max_depth=5, compress=False): |
| 19 | """ |
| 20 | dump into json, including only basic types, list types and dict types. |
| 21 | If other types are included, they will be converted into string. |
| 22 | """ |
| 23 | if max_depth <= 0: |
| 24 | return "..." |
| 25 | if isinstance(obj, (int, float, str, bool, type(None))): |
| 26 | return obj |
| 27 | elif isinstance(obj, list) or isinstance(obj, tuple): |
| 28 | if not compress or len(obj) <= 5: |
| 29 | return [serialize(item, max_depth - 1, compress) for item in obj] |
| 30 | else: |
| 31 | return [serialize(item, max_depth - 1, True) for item in obj[:5]] + [ |
| 32 | "...(total: %d)" % len(obj) |
| 33 | ] |
| 34 | elif isinstance(obj, dict): |
| 35 | if not compress or len(obj) <= 5: |
| 36 | return { |
| 37 | str(key): serialize(obj[key], max_depth - 1, compress) for key in obj |
| 38 | } |
| 39 | else: |
| 40 | ret = { |
| 41 | str(key): serialize(obj[key], max_depth - 1, True) |
| 42 | for key in list(obj.keys())[:5] |
| 43 | } |
| 44 | ret["...total..."] = len(obj) |
| 45 | return ret |
| 46 | elif hasattr(obj, "__dict__"): |
| 47 | return serialize(obj.__dict__, max_depth, True) |
| 48 | else: |
| 49 | ret = str(obj) |
| 50 | if len(ret) > 100: |
| 51 | ret = ret[:45] + " ... " + ret[-45:] |
| 52 | return ret |
| 53 | |
| 54 | |
| 55 | class ColorMessage: |
nothing calls this directly
no outgoing calls
no test coverage detected