Skip to content

RecursionError in generated code with nested properties #2337

@kampelmuehler

Description

@kampelmuehler

Describe the bug
Generated python code with nested properties causes pydantic v2 to be stuck in infinite loop.

To Reproduce

Example schema:

{
  "title": "Test",
  "type": "object",
  "properties": {
    "TestObject": {
      "title": "TestObject",
      "type": "object",
      "properties": {
        "test_string": {
          "type": "string"
        }
      }
    }
  }
}

Used commandline:

$ datamodel-codegen --input sample.json --output sample.py

then run python -c "from sample import Test"

which throws a RecursionError: maximum recursion depth exceeded

Mind you that this used to work just fine with pydantic v1 , but breaks in v2. Probably related to pydantic/pydantic#6646 (comment).

In the generated python code

[...]
class TestObject(BaseModel):
    test_string: Optional[str] = None


class Test(BaseModel):
    TestObject: Optional[TestObject] = Field(None, title='TestObject')

we could solve the issue by renaming class TestObject(BaseModel) to for example class TestObject_(BaseModel).

Expected behavior
Don't generate output code with namespace collision.

Version:

python==3.12.3
datamodel-code-generator==0.28.2                
pydantic==2.10.6
pydantic_core==2.27.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinghelp wantedExtra attention is needed

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions