From 2db23829ea759582bc3b05419df3abcc59d9df17 Mon Sep 17 00:00:00 2001 From: Yasser Mohammad Date: Wed, 25 Dec 2024 20:37:24 +0900 Subject: [PATCH] python_class_identifier in to_dict during serialization --- src/negmas/serialization.py | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/src/negmas/serialization.py b/src/negmas/serialization.py index 4f52f21c..31eec261 100644 --- a/src/negmas/serialization.py +++ b/src/negmas/serialization.py @@ -163,11 +163,16 @@ def get_type_field(value): ) ) - def convertwith(value, method): + def convertwith(value, method, pass_identifier=False): if hasattr(value, method) and isinstance( getattr(value, method), types.MethodType ): - converted = getattr(value, method)() # type: ignore + if pass_identifier: + converted = getattr(value, method)( + python_class_identifier=python_class_identifier + ) # type: ignore + else: + converted = getattr(value, method)() # type: ignore if isinstance(converted, dict): if add_type_field and (python_class_identifier not in converted.keys()): converted[python_class_identifier] = get_type_field(value) @@ -175,8 +180,11 @@ def convertwith(value, method): else: return adjust_dict(converted) + converted = convertwith(value, "to_dict", pass_identifier=True) + if converted is not None: + return converted for method in ("to_dict", "asdict", "dict"): - converted = convertwith(value, method) + converted = convertwith(value, method, pass_identifier=False) if converted is not None: return converted if isinstance(value, str): @@ -368,8 +376,15 @@ def good_field(k: str): if good_field(k) } # deserialize needs to do a shallow conversion from a dict as deep conversion is taken care of already. + # if hasattr(python_class, "from_dict"): - return python_class.from_dict({k: v for k, v in d.items()}) # type: ignore + try: + return python_class.from_dict( + {k: v for k, v in d.items()}, + python_class_identifier=python_class_identifier, + ) # type: ignore + except Exception: + return python_class.from_dict({k: v for k, v in d.items()}) # type: ignore if deep: d = { k: deserialize(