Datamodel-code-generator: Flag to use strict types in generated code

Created on 1 Mar 2021  路  3Comments  路  Source: koxudaxi/datamodel-code-generator

Is your feature request related to a problem? Please describe.
I'd love to be able to strictly validate primitive types (int, str, bool, ...) instead of silently having pydantic consider that 1 is a valid str.

Describe the solution you'd like
A flag such as --strict-primitive-types or --strict-types that will result in the generated code to use Strict* (e.g. StrictStr) instead of str, int, etc. It could also be more granular, e.g. --strict-str, --strict-int, or --strict-types int str bool (--strict-types [type1] [type2] [...]).

Describe alternatives you've considered
I don't think there is any alternative apart from manually writing the model 馃槢.

Additional context
Example without the flag:

class User(BaseModel):
    id: int = Field(..., description="Id of the user")
    username: str = Field(..., description="Username")

And with the flag:

class User(BaseModel):
    id: StrictInt = Field(..., description="Id of the user")
    username: StrictStr = Field(..., description="Username")

Thank you for this great tool!

enhancement released

Most helpful comment

@koxudaxi, works like a charm! Thanks a lot.

All 3 comments

@mboutet
Thank you for creating this issue.
I feel your suggestion is great 馃槃

--strict-types int str bool (--strict-types [type1] [type2] [...]).

I prefer this style. And, I will add all as choices.

I'm working on developing the next minor version. (0.9.0) https://github.com/koxudaxi/datamodel-code-generator/issues/357
I will implement your request after it is released.

@mboutet
I have released a new version as 0.9.1
I add this option!!

  --strict-types {str,bytes,int,float,bool} [{str,bytes,int,float,bool} ...]
                        Use strict types

@koxudaxi, works like a charm! Thanks a lot.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MikeZaharov picture MikeZaharov  路  3Comments

FlorianLudwig picture FlorianLudwig  路  3Comments

Gowee picture Gowee  路  3Comments

ioggstream picture ioggstream  路  6Comments

Echronix picture Echronix  路  3Comments