Skip to content

Commit 2db2382

Browse files
committed
python_class_identifier in to_dict during serialization
1 parent ca20bbc commit 2db2382

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

src/negmas/serialization.py

+19-4
Original file line numberDiff line numberDiff line change
@@ -163,20 +163,28 @@ def get_type_field(value):
163163
)
164164
)
165165

166-
def convertwith(value, method):
166+
def convertwith(value, method, pass_identifier=False):
167167
if hasattr(value, method) and isinstance(
168168
getattr(value, method), types.MethodType
169169
):
170-
converted = getattr(value, method)() # type: ignore
170+
if pass_identifier:
171+
converted = getattr(value, method)(
172+
python_class_identifier=python_class_identifier
173+
) # type: ignore
174+
else:
175+
converted = getattr(value, method)() # type: ignore
171176
if isinstance(converted, dict):
172177
if add_type_field and (python_class_identifier not in converted.keys()):
173178
converted[python_class_identifier] = get_type_field(value)
174179
return adjust_dict({k: v for k, v in converted.items()})
175180
else:
176181
return adjust_dict(converted)
177182

183+
converted = convertwith(value, "to_dict", pass_identifier=True)
184+
if converted is not None:
185+
return converted
178186
for method in ("to_dict", "asdict", "dict"):
179-
converted = convertwith(value, method)
187+
converted = convertwith(value, method, pass_identifier=False)
180188
if converted is not None:
181189
return converted
182190
if isinstance(value, str):
@@ -368,8 +376,15 @@ def good_field(k: str):
368376
if good_field(k)
369377
}
370378
# deserialize needs to do a shallow conversion from a dict as deep conversion is taken care of already.
379+
#
371380
if hasattr(python_class, "from_dict"):
372-
return python_class.from_dict({k: v for k, v in d.items()}) # type: ignore
381+
try:
382+
return python_class.from_dict(
383+
{k: v for k, v in d.items()},
384+
python_class_identifier=python_class_identifier,
385+
) # type: ignore
386+
except Exception:
387+
return python_class.from_dict({k: v for k, v in d.items()}) # type: ignore
373388
if deep:
374389
d = {
375390
k: deserialize(

0 commit comments

Comments
 (0)