Skip to content

Use RecursionError to check for circular references in json.dumps #134935

Closed as not planned
@aivarsk

Description

@aivarsk

Feature or enhancement

Proposal:

I was looking at several Python JSON encoders that are faster than Python's json module. One thing they do not do is checking for circular references. Instead they rely on RecursionError^H^H^H^H^H^H^H custom recursion limit to do it for them:

ultrajson gives you OverflowError: Maximum recursion level reached
orjson gives you a TypeError: Recursion limit reached.

I tried comparing json.dumps() with json.dumps(check_circular=False) and it gave 15% on a JSON used in JSON library comparison. The result might be different for different use cases.

But I think having extra code to track references just to raise a nicer ValueError is a bit too much. I have a patch that removes the extra code and tries to keep everything backward compatible. Could remove even more by removing markers from c_make_encoder and _make_iterencode but that requires fixes to some tests and maybe it breaks something.

Anyway, open to feedback.

# Add a code block here, if required

Has this already been discussed elsewhere?

No response given

Links to previous discussion of this feature:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-featureA feature request or enhancement

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions