Pydantic: Recursion error when generating schema

Created on 20 May 2019  路  3Comments  路  Source: samuelcolvin/pydantic


Bug

For bugs/questions:

  • OS: ubuntu 18.04
  • Python version import sys; print(sys.version): 3.7.3
  • Pydantic version import pydantic; print(pydantic.VERSION): 0.25

Running the code below to generate schema causes a recursion error.

from __future__ import annotations
import typing
from pydantic import BaseModel, Schema

class Account(BaseModel):
  name: str
  subaccounts: typing.List[Account] = []

Account.update_forward_refs()
print(Account.schema_json(indent=2))
...

Snippet of recursion traceback

...
   flat_models |= get_flat_models_from_model(field.type_)
  File "/home/nav/.local/share/virtualenvs/project-oxBoBmI4/lib/python3.7/site-packages/pydantic/schema.py", line 355, in get_flat_models_from_model
    flat_models |= get_flat_models_from_fields(fields)
  File "/home/nav/.local/share/virtualenvs/project-oxBoBmI4/lib/python3.7/site-packages/pydantic/schema.py", line 394, in get_flat_models_from_fields
    flat_models |= get_flat_models_from_field(field)
  File "/home/nav/.local/share/virtualenvs/project-oxBoBmI4/lib/python3.7/site-packages/pydantic/schema.py", line 373, in get_flat_models_from_field
    elif lenient_issubclass(field.type_, main.BaseModel):
  File "/home/nav/.local/share/virtualenvs/project-oxBoBmI4/lib/python3.7/site-packages/pydantic/utils.py", line 232, in lenient_issubclass
    return isinstance(cls, type) and issubclass(cls, class_or_tuple)
  File "/home/nav/.local/share/virtualenvs/project-oxBoBmI4/lib/python3.7/abc.py", line 143, in __subclasscheck__
    return _abc_subclasscheck(cls, subclass)
RecursionError: maximum recursion depth exceeded in comparison
bug

Most helpful comment

Awesome, thank you. I think you're the best person to do it since you understand schema best.

All 3 comments

I'm not sure what the correct behaviour would be here?

Since the model is self referencing, the schema surely is infinitely recursive?

@tiangolo do you have an idea about what to do here? Maybe just a more constructive error.

Yes, it should be able to create the JSON Schema, assign an ID to it and then reference it with $ref. Here's the relevant section in the spec: http://json-schema.org/latest/json-schema-core.html#rfc.section.8.3

I'll try to fix it as soon as I get a chance.

Awesome, thank you. I think you're the best person to do it since you understand schema best.

Was this page helpful?
0 / 5 - 0 ratings