Skip to content

simplify recursive refs #60

@adriangb

Description

@adriangb

I'm not sure if this would be possible (I'm guessing it's not), but it would be nice to be able to recursively refer to a parent validator without having to know a-priori if it will be recursive or not.

Currently, if you are parsing something like:

class Outer:
    inner: List[Outer]

You would have to know that Outer is recursive before you parse its fields.

Would it be possible to have an optional "id" property on every validator that acts as the reference for recursive schemas instead of a special "recursive-container" validator? So:

from typing import List

from pydantic_core import SchemaValidator


class Outer:
    inner: "List[Outer]"


v = SchemaValidator(
    {
        "type": "model-class",
        # id is optional, required for this to be usable as a recursive ref
        # the value is arbitrary, the id of the type seems like a safe choice
        "id": str(id(Outer)),
        "schema": {
            "type": "model",
            "fields": {
                "inner": {
                    "type": "list",
                    "items": {
                        "type": "recursive-ref",
                        "id": str(id(Outer)),
                    }
                },
            },
        },
    }
)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions