datamodel-code-generator icon indicating copy to clipboard operation
datamodel-code-generator copied to clipboard

Use Annotated instead of cons variants

Open gaborbernat opened this issue 4 years ago • 2 comments
trafficstars

The cons variants are not supported by mypy, instead one can use the Annotated form:

class A(BaseModel):
     p: constr(min_length=1)

Because the type here becomes constr that to the type checker seems a new type, not a variant of str: https://www.python.org/dev/peps/pep-0593/ With the introduction of PEP-593 now instead one should do:

class A(BaseModel):
     p: Annotated[str, Field(min_length=1)]

Now mypy will handle correctly both A().p and A().p = "b".

For more details see https://github.com/samuelcolvin/pydantic/issues/156

gaborbernat avatar Aug 10 '21 13:08 gaborbernat

@gaborbernat Thank you for suggesting the idea. I know about Annotated. I will implement the feature as a CLI option. :wink:

koxudaxi avatar Aug 11 '21 15:08 koxudaxi

@gaborbernat A version 0.11.12 supports --use-annotated option.

https://github.com/koxudaxi/datamodel-code-generator/blob/55eab4fb418555a2088f49346a4b0f212a823bb4/tests/data/expected/main/main_use_annotated_with_field_constraints/output.py#L34-L40

koxudaxi avatar Aug 27 '21 17:08 koxudaxi