Skip to content

Commit 2faf686

Browse files
committed
improved logic of Json Compressor: removed None values (since they serialised back as None, and added Type_Safe__Primitive support)
1 parent 5376adf commit 2faf686

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

osbot_utils/type_safe/type_safe_core/shared/Type_Safe__Json_Compressor.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from typing import Dict, Any, Type
2+
from osbot_utils.type_safe.Type_Safe__Primitive import Type_Safe__Primitive
23
from osbot_utils.type_safe.Type_Safe__Base import Type_Safe__Base
34
from osbot_utils.type_safe.Type_Safe import Type_Safe
45
from osbot_utils.type_safe.type_safe_core.shared.Type_Safe__Cache import type_safe_cache
@@ -23,7 +24,9 @@ def compress(self, obj: Any) -> dict:
2324
return compressed
2425

2526
def compress_object(self, obj: Any) -> Any:
26-
if isinstance(obj, Type_Safe):
27+
if isinstance(obj, Type_Safe__Primitive):
28+
return obj.__to_primitive__()
29+
elif isinstance(obj, Type_Safe):
2730
annotations = type_safe_cache.get_obj_annotations(obj)
2831
return self.process_type_safe_object(obj, annotations)
2932
elif isinstance(obj, dict):
@@ -41,6 +44,8 @@ def process_type_safe_object(self, obj : Type_Safe ,
4144
) -> Dict:
4245
result = {}
4346
for key, value in obj.__dict__.items():
47+
if value is None:
48+
continue
4449
if key.startswith('_'): # Skip internal attributes
4550
continue
4651
if key in annotations:
@@ -53,8 +58,12 @@ def process_type_safe_object(self, obj : Type_Safe ,
5358
def compress_annotated_value(self, value : Any ,
5459
annotation : Any
5560
) -> Any:
61+
if value is None:
62+
return None
5663
origin = type_safe_cache.get_origin(annotation)
57-
if origin in (type, Type): # Handle Type annotations
64+
if isinstance(value, Type_Safe__Primitive):
65+
return value.__to_primitive__()
66+
elif origin in (type, Type): # Handle Type annotations
5867
if value:
5968
return self.type_registry.register_type(class_full_name(value))
6069
return None
@@ -69,10 +78,14 @@ def compress_annotated_value(self, value : Any ,
6978
def compress_dict(self, data: Dict) -> Dict:
7079
if not isinstance(data, dict):
7180
return data
72-
7381
result = {}
7482
for key, value in data.items():
75-
compressed_key = self.compress_object(key) if isinstance(key, Type_Safe) else key
83+
if isinstance(value, Type_Safe__Primitive):
84+
compressed_key = value.__to_primitive__()
85+
elif isinstance(key, Type_Safe):
86+
compressed_key = self.compress_object(key)
87+
else:
88+
compressed_key=str(key)
7689
compressed_value = self.compress_object(value)
7790
result[compressed_key] = compressed_value
7891
return result

0 commit comments

Comments
 (0)