-
-
Notifications
You must be signed in to change notification settings - Fork 297
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
in python could we sometimes use default_factory
instead of default
?
#2076
Comments
EDIT: I am aware that you can use e.g. (for python) Book:
...
properties:
...
authors:
description: |-
The book author or authors
type: array
items:
type: string
default-factory: 'list'
editors:
description: |-
The editors of the book
type: array
items:
type: string
default-factory: 'lambda: ["nobody"]' however this is not a language-agnostic approach, this not imo an appropriate solution. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When generating a definitions from a schema, if defaults are used for dictionaries or arrays, datamodel-code-generator currently creates models using the
default
keyword for fields. In my opinion, this should really be thedefault_factory
keyword.NOTE: Fortunately, when using pydantic the use of
default
as opposed todefault_factory
does not result in the typical issue of the shared instances. However, I am not entirely sure of this is intentional or merely a happy coincidence. If were to switch things to factories,datamodel-code-generator
would be a tick safer.Example
Suppose I have a definition
then, when using datamodel-code-generator, I expect that the defaults of lists be treated as factories. Instead, when one calls, e.g.
python3 -m datamodel_code_generator \ --input-file-type openapi \ --output-model-type pydantic_v2.BaseModel \ --encoding "UTF-8" \ --disable-timestamp \ --use-schema-description \ --use-standard-collections \ --collapse-root-models \ --use-default-kwarg \ --field-constraints \ --capitalise-enum-members \ --enum-field-as-literal one \ --set-default-enum-member \ --use-subclass-enum \ --allow-population-by-field-name \ --snake-case-field \ --strict-nullable \ --use-double-quotes \ --target-python-version 3.11 \ --input myschema.yaml \ --output src/mymodels.py
one gets
The request here, is that this be changed to:
What could go wrong
By not using factories, two instances of a class can end up sharing the same attribute. E.g.
Note again, that I am not claiming that this happens with the pydantic models. In fact, the above does not happen. But, as stated at the start, it is not clear to me whether this be by design (of pydantic's
BaseModel
s/Field
s) simply a happy coincidence.Further context
python>=3.11
datamodel-code-generator>=0.25.9
pydantic>=2.8.2
The text was updated successfully, but these errors were encountered: