Skip to content

gh-94345: Fix dataclasses.asdict()/astuple() crash on circular references#151904

Open
iamsharduld wants to merge 1 commit into
python:mainfrom
iamsharduld:local-gh-94345-dataclasses-recursive
Open

gh-94345: Fix dataclasses.asdict()/astuple() crash on circular references#151904
iamsharduld wants to merge 1 commit into
python:mainfrom
iamsharduld:local-gh-94345-dataclasses-recursive

Conversation

@iamsharduld

@iamsharduld iamsharduld commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

asdict() and astuple() recurse into nested dataclasses and built-in containers without tracking which objects are already being processed, so a circular reference recurses until a RecursionError (or crashes the interpreter on a release build).

This tracks the objects on the current recursion path and raises ValueError("Circular reference detected") — matching json.dumps() — when one is revisited. Objects referenced more than once without forming a cycle (a DAG) are still converted normally.

…references

asdict() and astuple() recursed into nested dataclasses and containers
without tracking which objects were already being processed, so a circular
reference recursed until a RecursionError (or crashed the interpreter on a
release build). Track the objects on the current recursion path and raise
ValueError("Circular reference detected") -- matching json.dumps() -- when
one is revisited.
@read-the-docs-community

Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #33242498 | 📁 Comparing 4fb24e5 against main (476b649)

  🔍 Preview build  

2 files changed
± library/dataclasses.html
± whatsnew/changelog.html

@@ -0,0 +1,4 @@
:func:`dataclasses.asdict` and :func:`dataclasses.astuple` now raise
:exc:`ValueError` when the dataclass instance contains a circular reference,
instead of recursing until a :exc:`RecursionError` (or crashing on a release

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a crash on release builds (e.g. segmentation fault) or a python exception?

reference.

.. versionchanged:: next
A circular reference now raises :exc:`ValueError` instead of

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PR adds overhead to the conversion to dict or tuple. Can you benchmark this?

Adding overhead just to change the type of error message might be ok, but I would like to have some quantative numbers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants