datamodel-code-generator
datamodel-code-generator copied to clipboard
Two variations of syntaxes for defining dictionaries/free-form objects give different results
Describe the bug
According to this OpenAPI guide, there are two ways to define free-form objects (a.k.a., a dictionary with values of any type).
They are equivalent and we expect the code generator to produce the same results Optional[Dict[str, Any]] = None.
Unfortunately only one of the syntaxes works as expected.
To Reproduce
Example schema with syntax 1 (additionalProperties: true)
components:
schemas:
CustomObject:
type: object
properties:
config:
$ref: '#/components/schemas/Config'
Config:
type: object
additionalProperties: true
Output of syntax 1
class Config(BaseModel):
pass
model_config = ConfigDict(
extra="allow",
)
class CustomObject(BaseModel):
config: Optional[Config] = None
Example schema with syntax 2 (additionalProperties: {})
components:
schemas:
CustomObject:
type: object
properties:
config:
$ref: '#/components/schemas/Config'
Config:
type: object
additionalProperties: {}
Output of syntax 2
class CustomObject(BaseModel):
config: Optional[Dict[str, Any]] = None
Used commandline:
$ datamodel-codegen --input test.yaml --input-file-type openapi --output test.py --snake-case-field --target-python-version 3.9 --use-schema-description --field-constraints --use-annotated --collapse-root-models --use-one-literal-as-default --enum-field-as-literal one --output-model-type pydantic_v2.BaseModel
Expected behavior We expect both syntaxes will result in Output of syntax 2.
Version:
- OS: macOS Ventura 13.6.1
- Python version: 3.9.18
- datamodel-code-generator version: 0.22.1, 0.25.1
@shuangwu5 I'm sorry for my late reply. I agree with you. I guess this is a bug. we should fix it.