Recursively finds size of objects
(obj: Any, max_size: int, current_size: int = 0)
| 1071 | |
| 1072 | |
| 1073 | def get_size(obj: Any, max_size: int, current_size: int = 0) -> int: |
| 1074 | """Recursively finds size of objects""" |
| 1075 | if current_size >= max_size: |
| 1076 | return current_size |
| 1077 | |
| 1078 | obj_type = type(obj) |
| 1079 | |
| 1080 | # Check to see if the obj has a constant size estimate |
| 1081 | try: |
| 1082 | return _CONSTANT_SIZE_TABLE[obj_type] |
| 1083 | except KeyError: |
| 1084 | pass |
| 1085 | |
| 1086 | # Check to see if the obj has a variable but simple size estimate |
| 1087 | try: |
| 1088 | return _VARIABLE_SIZE_TABLE[obj_type](obj) |
| 1089 | except KeyError: |
| 1090 | pass |
| 1091 | |
| 1092 | # Special cases that require recursion |
| 1093 | if obj_type == Code: |
| 1094 | if obj.scope: |
| 1095 | current_size += ( |
| 1096 | 5 + get_size(obj.scope, max_size, current_size) + len(obj) - len(obj.scope) |
| 1097 | ) |
| 1098 | else: |
| 1099 | current_size += 5 + len(obj) |
| 1100 | elif obj_type == dict: |
| 1101 | for k, v in obj.items(): |
| 1102 | current_size += get_size(k, max_size, current_size) |
| 1103 | current_size += get_size(v, max_size, current_size) |
| 1104 | if current_size >= max_size: |
| 1105 | return current_size |
| 1106 | elif hasattr(obj, "__iter__"): |
| 1107 | for i in obj: |
| 1108 | current_size += get_size(i, max_size, current_size) |
| 1109 | if current_size >= max_size: |
| 1110 | return current_size |
| 1111 | return current_size |
| 1112 | |
| 1113 | |
| 1114 | def _truncate_documents(obj: Any, max_length: int) -> Tuple[Any, int]: |