datavalue 0.1.6__tar.gz → 0.1.7__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: datavalue
3
- Version: 0.1.6
3
+ Version: 0.1.7
4
4
  Summary: Librería de tipos de datos primitivos y complejos
5
5
  Author: Specter
6
6
  Requires-Python: >=3.10
@@ -2,6 +2,7 @@
2
2
  from typing import Type, Optional, Any, Iterable
3
3
  from .. import exceptions
4
4
  from .primitive_data import PrimitiveData
5
+ import json
5
6
 
6
7
  # Classes definition
7
8
  class ComplexData:
@@ -95,7 +96,129 @@ class ComplexData:
95
96
 
96
97
  return True
97
98
 
99
+ def _serialize_recursive(self, element: Any) -> Any:
100
+ # 1. Caso: Instancias de tus clases
101
+ if isinstance(element, (PrimitiveData, ComplexData)):
102
+ return {
103
+ "__type__": element.__class__.__name__,
104
+ "content": element.to_dict()
105
+ }
106
+
107
+ # 2. Caso: Tipos de datos (clases como str, int, dict)
108
+ if isinstance(element, type):
109
+ return {"__class__": element.__name__}
110
+
111
+ # 3. Caso: Colecciones estándar (recursión profunda)
112
+ if isinstance(element, (list, tuple, set, frozenset)):
113
+ return [self._serialize_recursive(i) for i in element]
114
+
115
+ if isinstance(element, dict):
116
+ return {str(k): self._serialize_recursive(v) for k, v in element.items()}
117
+
118
+ # 4. Caso: Literales serializables (int, str, float, bool, None)
119
+ return element
120
+
121
+ def _deserialize_recursive(self, element: Any) -> Any:
122
+ SAFE_TYPES = {
123
+ "list": list, "tuple": tuple, "set": set, "frozenset": frozenset,
124
+ "dict": dict, "str": str, "int": int, "float": float, "bool": bool,
125
+ "bytes": bytes, "bytearray": bytearray
126
+ }
127
+
128
+ # A. Manejo de Diccionarios (Estructuras u Objetos Serializados)
129
+ if isinstance(element, dict):
130
+ # Caso 1: Es un objeto serializado (PrimitiveData o ComplexData)
131
+ if "__type__" in element:
132
+ obj_type = element["__type__"]
133
+ content = element["content"]
134
+
135
+ if obj_type == "PrimitiveData":
136
+ return PrimitiveData(value=None, data_type=None, data_class=True).from_dict(content)
137
+ elif obj_type == "ComplexData":
138
+ return self.from_dict(content)
139
+ else:
140
+ raise ValueError(f"Unknown serialized object type: {obj_type}")
141
+
142
+ # Caso 2: Es una referencia a un tipo de clase (__class__)
143
+ if "__class__" in element:
144
+ type_name = element["__class__"]
145
+ if type_name in SAFE_TYPES:
146
+ return SAFE_TYPES[type_name]
147
+ raise ValueError(f"Type '{type_name}' is not allowed or unknown.")
148
+
149
+ # Caso 3: Es un diccionario de datos común (recurse keys & values)
150
+ return {k: self._deserialize_recursive(v) for k, v in element.items()}
151
+
152
+ # B. Manejo de Listas (recurse items)
153
+ if isinstance(element, list):
154
+ return [self._deserialize_recursive(item) for item in element]
155
+
156
+ # C. Literales (retorno directo)
157
+ return element
158
+
159
+
98
160
  # Public methods
161
+ def to_dict(self) -> dict:
162
+ return {
163
+ "DATA_TYPE":self.data_type.__name__ if hasattr(self.data_type, '__name__') else str(self.data_type),
164
+ "VALUE":self._serialize_recursive(self.value),
165
+ "MAXIMUM_LENGTH":self.maximum_length,
166
+ "MINIMUM_LENGTH":self.minimum_length,
167
+ "POSSIBLE_VALUES":self._serialize_recursive(self.possible_values) if self.possible_values is not None else None,
168
+ "DATA_CLASS":self.data_class
169
+ }
170
+
171
+
172
+ def from_dict(self, data: dict) -> 'ComplexData':
173
+ # 1. Secure types mapping
174
+ SAFE_TYPES = {
175
+ "list": list, "tuple": tuple, "set": set, "frozenset": frozenset,
176
+ "dict": dict, "str": str, "int": int, "float": float, "bool": bool,
177
+ "bytes": bytes, "bytearray": bytearray
178
+ }
179
+
180
+ # 3. Validación y Reconstrucción del Root
181
+ # Recuperamos el tipo de dato principal
182
+ raw_type = data.get("DATA_TYPE")
183
+ data_type = SAFE_TYPES.get(raw_type)
184
+ if not data_type:
185
+ raise TypeError(f"Invalid root data type: {raw_type}")
186
+
187
+ # Procesamos los possible_values con el motor recursivo
188
+ raw_possible = data.get("POSSIBLE_VALUES")
189
+ possible_values = self._deserialize_recursive(raw_possible) if raw_possible is not None else None
190
+
191
+ # Corrección de tipo para tuplas (JSON no tiene tuplas, devuelve listas)
192
+ # Si su __init__ es estricto y requiere tupla para possible_values, convertimos aquí:
193
+ if isinstance(possible_values, list) and data_type != dict:
194
+ possible_values = tuple(possible_values)
195
+
196
+ # Para dicts, mantenemos la lista de listas o convertimos según su preferencia estricta
197
+ if isinstance(possible_values, list) and data_type == dict:
198
+ # Opcional: convertir sub-listas a tuplas si su validador lo prefiere,
199
+ # aunque su validación actual acepta listas.
200
+ pass
201
+
202
+ return ComplexData(
203
+ data_type=data_type,
204
+ value=data.get("VALUE"), # Asumimos valor literal o serializable simple
205
+ maximum_length=data.get("MAXIMUM_LENGTH"),
206
+ minimum_length=data.get("MINIMUM_LENGTH"),
207
+ possible_values=possible_values,
208
+ data_class=data.get("DATA_CLASS", False)
209
+ )
210
+
211
+
212
+ def from_json(self, text_content: str) -> 'ComplexData':
213
+ try:
214
+ data = json.loads(text_content)
215
+ except json.JSONDecodeError as e:
216
+ raise ValueError(f"Invalid JSON: {e}")
217
+ return self.from_dict(data)
218
+
219
+ def to_json(self) -> str:
220
+ return json.dumps(self.to_dict(), indent=4)
221
+
99
222
  def validate(self, data: Any = None) -> bool:
100
223
  # Determine objective data
101
224
  if data is None:
@@ -59,15 +59,58 @@ class PrimitiveData:
59
59
  def to_json(self) -> str:
60
60
  return json.dumps(self.to_dict(), indent=4)
61
61
 
62
- def from_json(self, text_content: str) -> dict:
63
- data_table = json.loads(text_content)
64
- local_table = self.to_dict()
62
+
63
+ def from_dict(self, data: dict) -> 'PrimitiveData':
64
+ # Expected keys definition
65
+ expected_keys = {
66
+ "DATA_TYPE", "VALUE", "MAXIMUM_LENGTH", "MINIMUM_LENGTH",
67
+ "MAXIMUM_SIZE", "MINIMUM_SIZE", "POSSIBLE_VALUES",
68
+ "REGULAR_EXPRESSION", "DATA_CLASS"
69
+ }
70
+
71
+ # Verify unknown keys on the table
72
+ unknown_keys = set(data.keys()) - expected_keys
73
+ if unknown_keys:
74
+ raise ValueError(f"Unknown keys in data structure: {unknown_keys}")
75
+
76
+ # Secure type mapping
77
+ type_mapping = {
78
+ "str": str,
79
+ "int": int,
80
+ "float": float,
81
+ "bool": bool,
82
+ "bytes": bytes,
83
+ "bytearray": bytearray,
84
+ "NoneType": type(None)
85
+ }
86
+
87
+ type_str = data.get("DATA_TYPE")
88
+ real_type = type_mapping.get(type_str)
65
89
 
66
- for element in data_table:
67
- if element not in local_table: raise ValueError(f"The loaded table has a unknown value: {element}")
90
+ if real_type is None and type_str != "None":
91
+ raise TypeError(f"Unsupported or unsafe data type for deserialization: {type_str}")
68
92
 
69
- return data_table
93
+ # return instance result
94
+ return PrimitiveData(
95
+ data_type=real_type,
96
+ value=data.get("VALUE"),
97
+ maximum_length=data.get("MAXIMUM_LENGTH"),
98
+ minimum_length=data.get("MINIMUM_LENGTH"),
99
+ maximum_size=data.get("MAXIMUM_SIZE"),
100
+ minimum_size=data.get("MINIMUM_SIZE"),
101
+ possible_values=data.get("POSSIBLE_VALUES"),
102
+ regular_expression=data.get("REGULAR_EXPRESSION"),
103
+ data_class=data.get("DATA_CLASS", False)
104
+ )
70
105
 
106
+ def from_json(self, text_content: str) -> 'PrimitiveData':
107
+ try:
108
+ data_table = json.loads(text_content)
109
+ except json.JSONDecodeError as Error:
110
+ raise ValueError(f"Invalid JSON format: {Error}")
111
+
112
+ return self.from_dict(data_table)
113
+
71
114
  def validate(self, data: Optional[Any] = None) -> bool:
72
115
  # Define the data to validate
73
116
  if data is None:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: datavalue
3
- Version: 0.1.6
3
+ Version: 0.1.7
4
4
  Summary: Librería de tipos de datos primitivos y complejos
5
5
  Author: Specter
6
6
  Requires-Python: >=3.10
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "datavalue"
7
- version = "0.1.6"
7
+ version = "0.1.7"
8
8
  description = "Librería de tipos de datos primitivos y complejos"
9
9
  readme = "README.md"
10
10
  authors = [{ name="Specter" }]
File without changes
File without changes