def _asdict(obj, encode_json=False, include_cls=True): """ A re-implementation of `asdict` (based on the original in the `dataclasses` source) to support arbitrary Collection and Mapping types. """ if _is_dataclass_instance(obj): result = [] for field in fields(obj): value = _asdict(getattr(obj, field.name), encode_json=encode_json) result.append((field.name, value)) result = _handle_undefined_parameters_safe(cls=obj, kvs=dict(result), usage="to") # >>> INSERTED HERE if include_cls and hasattr(obj.__class__, "__pai_dataclass__"): result = dict(result) result["__cls__"] = obj.__class__.__module__ + ":" + obj.__class__.__name__ # <<< END return _encode_overrides(dict(result), _user_overrides_or_exts(obj), encode_json=encode_json) elif isinstance(obj, Mapping): return dict((_asdict(k, encode_json=encode_json), _asdict(v, encode_json=encode_json)) for k, v in obj.items()) elif isinstance(obj, Collection) and not isinstance(obj, str) and not isinstance(obj, bytes): return list(_asdict(v, encode_json=encode_json) for v in obj) else: return copy.deepcopy(obj)
def _asdict(obj, encode_json=False): """ A re-implementation of `asdict` (based on the original in the `dataclasses` source) to support arbitrary Collection and Mapping types. """ if _is_dataclass_instance(obj): result = [] for field in fields(obj): value = _asdict(getattr(obj, field.name), encode_json=encode_json) result.append((field.name, value)) result = _handle_undefined_parameters_safe(cls=obj, kvs=dict(result), usage="to") return _encode_overrides(dict(result), _user_overrides(obj), encode_json=encode_json) elif isinstance(obj, Mapping): return dict((_asdict(k, encode_json=encode_json), _asdict(v, encode_json=encode_json)) for k, v in obj.items()) elif isinstance(obj, Collection) and not isinstance(obj, str) \ and not isinstance(obj, bytes): return list(_asdict(v, encode_json=encode_json) for v in obj) else: return copy.deepcopy(obj)
def default(self, o: Any) -> Any: if isinstance(o, enum.Enum): return o.name elif dataclasses._is_dataclass_instance(o): return dataclasses.asdict(o) else: return json.JSONEncoder.default(self, o)
def asdict(obj, dict_factory=dict, filter_field_type=None): """ Version of dataclasses.asdict that can use field type infomation. """ if _is_dataclass_instance(obj): result = [] for f in fields(obj): if filter_field_type is None: continue field_type_from_metadata = f.metadata.get('type', None) if field_type_from_metadata != filter_field_type and field_type_from_metadata is not None: continue value = asdict(getattr(obj, f.name), dict_factory, filter_field_type) result.append((f.name, value)) return dict_factory(result) elif isinstance(obj, tuple) and hasattr(obj, '_fields'): return type(obj)(*[asdict(v, dict_factory, filter_field_type) for v in obj]) elif isinstance(obj, (list, tuple)): return type(obj)(asdict(v, dict_factory, filter_field_type) for v in obj) elif isinstance(obj, dict): return type(obj)((asdict(k, dict_factory, filter_field_type), asdict(v, dict_factory, filter_field_type)) for k, v in obj.items()) else: return copy.deepcopy(obj)
def __instancecheck__(self, instance: 'Any') -> bool: try: from dataclasses import _is_dataclass_instance except ImportError: # python 3.6 return False else: return _is_dataclass_instance(instance)
def _asdict_inner(obj, dict_factory): if _is_dataclass_instance(obj): result = [] for f in fields(obj): value = _asdict_inner(getattr(obj, f.name), dict_factory) result.append((f.metadata.get('property', f.name), value)) return dict_factory(result) elif isinstance(obj, (list, tuple)): return type(obj)(_asdict_inner(v, dict_factory) for v in obj) elif isinstance(obj, dict): return type(obj)( (_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory)) for k, v in obj.items()) else: return copy.deepcopy(obj)
def _asdict(obj): """ A re-implementation of `asdict` (based on the original in the `dataclasses` source) to support arbitrary Collection and Mapping types. """ if _is_dataclass_instance(obj): result = [] for f in fields(obj): value = _asdict(getattr(obj, f.name)) result.append((f.name, value)) return dict(result) elif isinstance(obj, Mapping): return dict((_asdict(k), _asdict(v)) for k, v in obj.items()) elif isinstance(obj, Collection) and not isinstance(obj, str): return list(_asdict(v) for v in obj) else: return obj
def _asdict_inner(obj, dict_factory): """Deserialize a dataclass into a dict_factory. It is still called _asdict_inner because it actually extends the functionality of the one which is used in dataclasses, but the behavior is changed in order to support optional fields. Notes: - If their value is equal to the defaulted optional value it will not appear in the deserialization. Args: obj: dataclass instance to be deserialized. dict_factory: If given it will be used instead of buildt-in dict. Returns: Deserialized class in the given dict_factory. """ if _is_dataclass_instance(obj): result = [] for f in fields(obj): try: # Optional fields which have the default_optional_value are # considered not defined and therefore they should not appear # on the deserialization. if f.optional and getattr( obj, f.name) == f.default_optional_value: continue except AttributeError: log.debug("A standard dataclass field is being deserialized") value = _asdict_inner(getattr(obj, f.name), dict_factory) result.append((f.name, value)) return dict_factory(result) elif isinstance(obj, (list, tuple)): return type(obj)(_asdict_inner(v, dict_factory) for v in obj) elif isinstance(obj, dict): return type(obj)( (_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory)) for k, v in obj.items()) else: if isinstance(obj, Enum): return copy.deepcopy(obj.value) else: return copy.deepcopy(obj)
def asdict(obj, *, dict_factory=dict): """Return the fields of a dataclass instance as a new dictionary mapping field names to field values. Example usage: @dataclass class C: x: int y: int c = C(1, 2) assert asdict(c) == {'x': 1, 'y': 2} If given, 'dict_factory' will be used instead of built-in dict. The function applies recursively to field values that are dataclass instances. This will also look into built-in containers: tuples, lists, and dicts. """ if not _is_dataclass_instance(obj): raise TypeError("asdict() should be called on dataclass instances") return _asdict_inner(obj, dict_factory)
def asdict(obj, dict_factory): if dataclasses._is_dataclass_instance(obj): result = [] for f in dataclasses.fields(obj): value = asdict(getattr(obj, f.name), dict_factory) result.append((f.name.replace('_', '-'), value)) return dict_factory(result) if isinstance(obj, tuple) and hasattr(obj, '_fields'): return type(obj)(*[asdict(v, dict_factory) for v in obj]) if isinstance(obj, (list, tuple)): return type(obj)(asdict(v, dict_factory) for v in obj) if isinstance(obj, dict): return type(obj)((asdict(k, dict_factory), asdict(v, dict_factory)) for k, v in obj.items()) return copy.deepcopy(obj)
def default(self, o) -> JSON: result: JSON if _isinstance_safe(o, Collection): if _isinstance_safe(o, Mapping): result = dict(o) else: result = list(o) elif _isinstance_safe(o, datetime): result = o.isoformat() elif _isinstance_safe(o, UUID): result = str(o) elif _isinstance_safe(o, Decimal): result = str(o) elif _isinstance_safe(o, Enum): result = o.value elif _is_dataclass_instance(o): result = asdict(o) else: result = json.JSONEncoder.default(self, o) return result
def _asdict_inner(obj, dict_factory): if _is_dataclass_instance(obj): result = [] for f in fields(obj): value = _asdict_inner(getattr(obj, f.name), dict_factory) result.append((f.name, value)) return dict_factory(result) elif isinstance(obj, (list, tuple)): return type(obj)(_asdict_inner(v, dict_factory) for v in obj) # Handle defaultdict correctly elif isinstance(obj, defaultdict): return type(obj)( obj.default_factory, ((_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory)) for k, v in obj.items())) # End fix elif isinstance(obj, dict): return type(obj)( (_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory)) for k, v in obj.items()) else: return copy.deepcopy(obj)
def update_event(self, inp=-1): self.set_output_val(0, dataclasses._is_dataclass_instance(self.input(0)))
def asdict(obj, *, dict_factory=dict): if not _is_dataclass_instance(obj): raise TypeError("asdict() should be called on dataclass instances") return _asdict_inner(obj, dict_factory)