Describe the bug
An OpenAPI schema with a self-referencing object with a discriminated union produces code with undefined variables for all output model types except pydantic v1 BaseModel.
To Reproduce
Example schema:
---
openapi: 3.1.0
components:
schemas:
Bar:
type: object
properties:
kind:
const: Bar
required:
- kind
Foo:
type: object
properties:
kind:
const: Foo
children:
type: array
items:
oneOf:
- "$ref": "#/components/schemas/Foo"
- "$ref": "#/components/schemas/Bar"
discriminator:
propertyName: kind
mapping:
Foo: "#/components/schemas/Foo"
Bar: "#/components/schemas/Bar"
title: Children
required:
- children
- kind
Used commandline:
$ datamodel-codegen --output-model-type typing.TypedDict
Output:
from __future__ import annotations
from typing import List, Union
from typing_extensions import NotRequired, TypedDict
class Bar(TypedDict):
kind: NotRequired[str]
Children = Union[Foo, Bar] # Foo is undefined!
class Foo(TypedDict):
kind: NotRequired[str]
children: List[Children]
Similar error happens for other output model types. Only pydantic v1 works because Foo
is a variable annotation, rather than in a Union
in a type alias.
Expected behavior
Reference to Foo
properly turned into forward reference
Version:
Additional context
It works properly if the discriminator
is removed from the schema.
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too