Skip to content

Missing recursion detection in attr.asdict #740

Open
@wimglenn

Description

@wimglenn

Suppose we use attrs instances to represent graphs:

>>> @attr.s
... class Node:
...     val = attr.ib()
...     linked_node = attr.ib(default=None)
... 
>>> n = Node(1)
>>> attr.asdict(n)
{'val': 1, 'linked_node': None}
>>> n.linked_node = n
>>> n
Node(val=1, linked_node=...)

Although the repr handles it, attr.asdict does not detect and resolve cycles - should it?

>>> d = attr.asdict(n)
...
---------------------------------------------------------------------------
RecursionError                            Traceback (most recent call last)
...
.venv/lib/python3.9/site-packages/attr/_funcs.py in asdict(inst, recurse, filter, dict_factory, retain_collection_types, value_serializer)
     60         if recurse is True:
     61             if has(v.__class__):
---> 62                 rv[a.name] = asdict(
     63                     v,
     64                     True,

RecursionError: maximum recursion depth exceeded while calling a Python object

Maybe this the intended behavior (if so, please close this issue), I'm not sure. But I half-expected a self-referencing dict to be returned:

>>> d
{'val': 1, 'linked_node': {...}}

Metadata

Metadata

Assignees

No one assigned

    Labels

    ThinkingNeeds more braining.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions