datamodel-code-generator
datamodel-code-generator copied to clipboard
Combining "required" and "default" leads to an optional property
Is your feature request related to a problem? Please describe.
Marking a property as required in combination of having a default value is still marked as optional in the Python module.
schema.json
{
"$id": "https://example.com/schema.json",
"$schema": "http://json-schema.org/draft/2020-12/schema",
"title": "Model",
"description": "Testing",
"type": "object",
"properties": {
"property_a": {
"type": "integer",
"default": 5
}
},
"required": ["property_a"]
}
datamodel-codegen --input schema.json \
--input-file-type jsonschema \
--disable-timestamp \
--use-default \
--output schema.py
schema.py
# generated by datamodel-codegen:
# filename: schema.json
from __future__ import annotations
from typing import Optional
from pydantic import BaseModel
class Model(BaseModel):
property_a: Optional[int] = 5
Even though "property_a" was marked as required it's listed as an Optional property in the model because the property also has a default value of 5.
Because of this mypy or other type hinting tools would complain if you did as below as "property_a" could also be None
stuff = Model()
print(stuff.property_a + 3)
Describe the solution you'd like
I think it would make more sense if the properties marked as required never got the Optional, or that there at least existed a way to make it behave in this way.
Describe alternatives you've considered Current workaround is to reassign the default value in code or create another variable