Missing recursion detection in attr.asdict

Open
#740 8 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
35/100
Issue type
Bug
Clarity
Needs clarification
Activity status
Stale
Tech stack
python
Domain
tooling

Research direction

Start by reading the asdict entry point in attr/_funcs.py shown in the traceback and reproduce the self-referencing Node example from the issue. Resolve the intended cycle behavior before implementing it, then add regression coverage; the issue is complete when recursive input has explicit, tested behavior instead of an unbounded RecursionError.

Written by the indexing model from the issue text.

Description

Thinking

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': {...}}
Dominant language
Python
Stars
5.8k
Forks
480
Avg merge
2h 15m
Merged PRs (30d)
2

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python-attrs/attrs

All issues in python-attrs/attrs

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.