MCPcopy Index your code
hub / github.com/RustPython/RustPython / _asdict_inner

Function _asdict_inner

Lib/dataclasses.py:1499–1564  ·  view source on GitHub ↗
(obj, dict_factory)

Source from the content-addressed store, hash-verified

1497
1498
1499def _asdict_inner(obj, dict_factory):
1500 obj_type = type(obj)
1501 if obj_type in _ATOMIC_TYPES:
1502 return obj
1503 elif hasattr(obj_type, _FIELDS):
1504 # dataclass instance: fast path for the common case
1505 if dict_factory is dict:
1506 return {
1507 f.name: _asdict_inner(getattr(obj, f.name), dict)
1508 for f in fields(obj)
1509 }
1510 else:
1511 return dict_factory([
1512 (f.name, _asdict_inner(getattr(obj, f.name), dict_factory))
1513 for f in fields(obj)
1514 ])
1515 # handle the builtin types first for speed; subclasses handled below
1516 elif obj_type is list:
1517 return [_asdict_inner(v, dict_factory) for v in obj]
1518 elif obj_type is dict:
1519 return {
1520 _asdict_inner(k, dict_factory): _asdict_inner(v, dict_factory)
1521 for k, v in obj.items()
1522 }
1523 elif obj_type is tuple:
1524 return tuple([_asdict_inner(v, dict_factory) for v in obj])
1525 elif issubclass(obj_type, tuple):
1526 if hasattr(obj, '_fields'):
1527 # obj is a namedtuple. Recurse into it, but the returned
1528 # object is another namedtuple of the same type. This is
1529 # similar to how other list- or tuple-derived classes are
1530 # treated (see below), but we just need to create them
1531 # differently because a namedtuple's __init__ needs to be
1532 # called differently (see bpo-34363).
1533
1534 # I'm not using namedtuple's _asdict()
1535 # method, because:
1536 # - it does not recurse in to the namedtuple fields and
1537 # convert them to dicts (using dict_factory).
1538 # - I don't actually want to return a dict here. The main
1539 # use case here is json.dumps, and it handles converting
1540 # namedtuples to lists. Admittedly we're losing some
1541 # information here when we produce a json list instead of a
1542 # dict. Note that if we returned dicts here instead of
1543 # namedtuples, we could no longer call asdict() on a data
1544 # structure where a namedtuple was used as a dict key.
1545 return obj_type(*[_asdict_inner(v, dict_factory) for v in obj])
1546 else:
1547 return obj_type(_asdict_inner(v, dict_factory) for v in obj)
1548 elif issubclass(obj_type, dict):
1549 if hasattr(obj_type, 'default_factory'):
1550 # obj is a defaultdict, which has a different constructor from
1551 # dict as it requires the default_factory as its first arg.
1552 result = obj_type(obj.default_factory)
1553 for k, v in obj.items():
1554 result[_asdict_inner(k, dict_factory)] = _asdict_inner(v, dict_factory)
1555 return result
1556 return obj_type((_asdict_inner(k, dict_factory),

Callers 1

asdictFunction · 0.85

Calls 6

hasattrFunction · 0.85
getattrFunction · 0.85
fieldsFunction · 0.85
dict_factoryFunction · 0.85
issubclassFunction · 0.85
itemsMethod · 0.45

Tested by

no test coverage detected