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