datamodel-code-generator icon indicating copy to clipboard operation
datamodel-code-generator copied to clipboard

Order of class definitions incorrect

Open jonasengelmann opened this issue 2 years ago • 0 comments

Describe the bug I have run into an issue with a somewhat complex inheritance structure. The order of class definitions of the generated model is incorrect, resulting in NameErrors. However, when I manually reorder the class definitions, everything works fine. I also noticed, that if all my classes do not have properties, the class definition order is correct too.

To Reproduce Example schema:

{
    "components": {
        "schemas": {
            "A": {
                "properties": {
                    "a_property": {
                        "$ref": "#/components/schemas/B1"
                    },
                },
                "type": "object"
            },
            "B1": {
                "allOf": [
                    {
                        "$ref": "#/components/schemas/A"
                    }
                ],
                "type": "object"
            },
            "C1": {
                "allOf": [
                    {
                        "$ref": "#/components/schemas/B1"
                    }
                ],
                "type": "object"
            },
            "B2": {
                "allOf": [
                    {
                        "$ref": "#/components/schemas/A"
                    }
                ],
                "type": "object"
            },
            "D1": {
                "allOf": [
                    {
                        "$ref": "#/components/schemas/C1"
                    }
                ],
                "type": "object"
            },
            "D1andB2": {
                "allOf": [
                    {
                        "$ref": "#/components/schemas/D1"
                    },
                    {
                        "$ref": "#/components/schemas/B2"
                    }
                ],
                "type": "object"
            },
        }
    }
}

Used commandline:

$ datamodel-codegen  --input test_schema.json --input-file-type openapi --output test_model.py

Generated Model

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel


class A(BaseModel):
    a_property: Optional[B1] = None


class B1(A):
    pass


class B2(A):
    pass


class C1(B1):
    pass


class D1andB2(D1, B2):
    pass


class D1(C1):
    pass


A.update_forward_refs()
B1.update_forward_refs()
B2.update_forward_refs()
C1.update_forward_refs()
D1andB2.update_forward_refs()
D1.update_forward_refs()

Expected behavior I expected that D1 is defined before D1andB2. However, it is not the case, resulting in a NameError.

Version:

  • OS: Mac
  • Python version: 3.9.12
  • datamodel-code-generator version: 0.13.1

jonasengelmann avatar Sep 06 '22 22:09 jonasengelmann