Skip to content

Releases

0.102.0

Choose a tag to compare

@github-actions github-actions released this 25 Nov 00:41
5beda2b

Breaking Changes

Code Generation Changes

  • A package class beside a same-named submodule no longer binds the class name through the import of the submodule's models - In dataclass, msgspec and TypedDict output the modules that use a model of the submodule now import it from the submodule, so they no longer bind the class name of the package (from .pkg import Warn) through that import. They read the class through it, and resolving their annotations (type hints, msgspec decoding) failed. (#7444)
  • A Pydantic package class beside a same-named submodule is refused where only the root package loads the submodule - Where a package's init.py defines a class named like one of its submodules and imports from the root package (from .. import common), the root's own import of the submodule (from .pkg import Warn) was taken as a load of the init.py. The root runs first, so that import ran after the class was defined and bound the class, and the root's model of the submodule (Warn.Detail) read the class. Where the classes evaluate their annotations as they are defined (Pydantic, which builds a class as it is defined, or output without from future import annotations) the root failed at import with AttributeError, so no module of the package imported: those runs now refuse the class as for other packages that do not load the submodule, and name --rename-submodules-hidden-by-classes. Dataclasses, TypedDict and msgspec with deferred annotations, where every module imported, keep their output; the stored outputs of the root-imported and cyclic layouts pin that. (#7444)
  • --recommend-options takes the target Python version from requires-python - Experimental: cli-option.recommend-options. When no option, pyproject.toml key or preset sets the target Python version, --recommend-options takes the lower bound of requires-python in the project's pyproject.toml (>=3.12, ~=3.12, ==3.12.*, with upper bounds or exclusions beside it), clamped to the supported targets and to the lowest one a client or server target supports, starts from that preset, and adds --target-python-version to the command and the pyproject.toml block with a note naming the source; other forms keep the note that the default is assumed. Generation never reads requires-python. (#7493)

API/CLI Changes

  • Public names for --apply-default-values-to-true-properties - The option adds its config field; nothing is removed or changed. (#7455)
  • Public names for --distribute-allof-over-object-branches - The option adds its config field; nothing is removed or changed. (#7445)
  • A store operation that names the classes of the additional properties - GraphBuilder.name_additional_properties_classes() (and GenerationStore.name_additional_properties_classes()) gives a model the type of its additional properties with the classes they name, which replace those recorded; nothing is removed or changed. (#7473)
  • A store operation that drops one entry of a field's extras - GraphBuilder.drop_field_extra() (and GenerationStore.drop_field_extra()) drops one key of a field's extras in place, as drop_field_discriminator() does for the discriminator; nothing is removed or changed. (#7494)
  • Store signatures name the graph classes, and its operations lose their deprecation markers - GenerationStore.seal_facts, FinalFacts and the union keyword methods of DataTypeManager name DataType, DataModel and Reference where they named the read-only views of model/_views.py, which are gone. The operations of GenerationStore lose their Daniel Edeling (@deprecated)(category=None) markers, which warned no caller at run time, and GraphBuilder(store) takes no token; heki keeps the package's own calls of the operations inside the generation store. (#7484)
  • Public names for --write-pyproject-config - The option adds a row to the option table and the fast path of --generate-prompt steps aside for it; nothing is removed or changed. (#7495)

New Warnings

  • A pydantic dataclass that redeclares an inherited field without a pattern Python's re rejects warns - Where a pydantic_v2.dataclass selects python-re for a look-around pattern of a base and another base has a pattern Python's re rejects, such as \p{L}, the dataclass redeclares that field of a base of its module without the pattern and warns that the field is generated without the constraint. Such a module failed at import before. (#7489)
  • Warn where an allOf over a union drops what the union checks - Without --distribute-allof-over-unions an allOf member naming an allOf over a union warns that the model checks none of its branches (#5305), and without --distribute-allof-over-object-branches so does a branch of an allOf's union that is itself a union or an alias (#6869). The generated output does not change. (#7445)

New Options

  • New option --apply-default-values-to-true-properties (--no-apply-default-values-to-true-properties): Give a property whose schema is true the default that --default-values gives it, in the class that declares it and in a child that restates an inherited property as true (name: str | None = 'rex' for Dog.name); without it such a property takes no default, as in 0.100.0 (#7455)
  • New option --distribute-allof-over-object-branches (--no-distribute-allof-over-object-branches): Give an allOf over an anyOf or oneOf one union variant per object branch, also where a branch is itself an anyOf or oneOf (named by a $ref or written there), an allOf or a $ref with sibling keywords over one, or an alias of an object schema, and have each variant require every name a part of the allOf requires, typed as the field it takes from its branch (allOf: [Pet, {required: [name]}] with Pet a oneOf of Cat and Dog that declare name optional). Without it such a branch gives a variant of the other members alone, or none, and warns, and a variant takes the name as its bases hold it, optional or Any, as in 0.100.0 (#7445)
  • New option --write-pyproject-config: Write the pyproject.toml table that --recommend-options or --generate-pyproject-config prints into the project's pyproject.toml, setting only the keys it adds or changes, and print what was written (experimental). (#7495)

New Dated Presets

  • standard-py3XX-20261124 and practical-py3XX-20261124: they keep the 20261123 options and add allOf distributed over object branches (--distribute-allof-over-object-branches): Give an allOf over an anyOf or oneOf one union variant per object branch, also where a branch is itself an anyOf or oneOf, named by a $ref or written there, and have each variant declare every name a part of the allOf requires as a required field, typed as its branch declares it, so a variant needs such a name, and output types that validate values reject one its branch rejects; Default values of true properties (--apply-default-values-to-true-properties): Under --default-values, give a property whose schema is true the default its Class.field or field key gives it, also where a child restates an inherited property as true, as a property whose schema is {} takes it. (#7455, #7445)

Experimental Features

  • --write-pyproject-config, its report, and the written key of the recommend-options and pyproject-config JSON payloads is experimental. Writing the pyproject.toml table is experimental; the file it chooses, the edits it refuses, and its report may change.

Changes That Need No Action

  • A package class beside a same-named submodule that its init.py loads first no longer hides the submodule's models - Where a package's init.py loads a submodule while its imports run (--all-exports-scope re-exports it, or a module it imports loads it) and also defines a class of the submodule's name, the modules that use a model of the submodule now import it from the submodule, as the output already did where the init.py names a type of the submodule. They read the class through the package: a Pydantic module failed at import with AttributeError, and the other backends failed where the annotations are resolved (type hints, msgspec decoding). They no longer bind the class name through that import. (#7444)
  • Select python-re in a pydantic dataclass that builds a base's lookaround - A pydantic_v2.dataclass whose config does not select python-re, such as one with its own config under --extra-fields, or one that takes the config of another first base, now selects it when a base it inherits has a pattern only Python's re reads, keeping every item of a config it took from a base, such as extra='forbid'. Such a module failed at import with a SchemaError. Where a base of its module also has a pattern Python's re rejects, such as \p{L}, the dataclass redeclares the inherited field without it and warns, and the base keeps its output. (#7489, #7452)
  • Read a boolean parameter schema as Any - An OpenAPI parameter or response header whose schema is true or false no longer stops the paths and parameters scopes with a validation error; the parameter is typed Any, like an empty schema. (#7483, #7454)
  • Flatten msgspec bases under --reuse-model by the models reuse merges - With --output-model-type msgspec.Struct, a model with two generated bases whose layouts still conflict once every module is processed stopped with incompatible layouts, for instance under --reuse-model when one base has the field names of another base's ancestor but a different type, default, description or constraint, or when a discriminator field of a base is not tagged. It declares the fields of its bases itself, as it does without --reuse-model. (#7446)
  • Show the warnings of msgspec runs that now generate - A msgspec run that stopped with incompatible layouts under --reuse-model now generates, so it shows the warnings its models raise, such as that msgspec cannot decode a union whose Struct types are not all tagged; a directory input shows those of every module, and the single-file attempt before its modular output now stops on the mod...
Read more

0.101.0

Choose a tag to compare

@github-actions github-actions released this 24 Nov 01:35
c115b0b

Breaking Changes

Code Generation Changes

  • A named allOf whose merged root is an enum class is written as that enum - A named allOf of an untyped constraint $ref and a typed enum member, such as allOf: [{$ref: ThreeLetters}, {type: string, enum: [GBP, JPY]}], stopped with "a $ref chain that loops back" for Pydantic and msgspec output, and under --collapse-root-models and the presets wrote a field or a root model that accepted no value of the enum; it is now written as its enum class, which accepts the values of the enum. Standard dataclasses keep Any without --intersect-merged-allof-members. (#7399, #7314)
  • AsyncAPI handshake parameters take the default of their model field - Experimental: cli-option.generate-client. A WebSocket handshake query or header parameter of a generated AsyncAPI client took the default at the end of its whole $ref chain, while the models take a referenced default one reference deep. The parameter now takes the default of its model field, so both agree: two references deep, or under --collapse-root-models or --ignore-ref-siblings-by-schema-version, the argument has no default where the model field has none. (#7394, #6975)
  • A reference to a component Multi Format Schema Object names the schema it holds - Experimental: input-format.asyncapi. A payload, headers or component $ref to a Multi Format Schema Object in components.schemas, also through component aliases, is typed by the JSON Schema the object holds: the RootModel[Any] read from the wrapper (NoteModel) is gone, the payload, headers and alias classes are root models over the held model, and the held model takes the component's name where the wrapper took it before (Tag1 is Tag). (#7389, #6936)
  • A directory input with hidden files that are not text generates the same models - The stored outputs of the directory inputs with hidden files; the models are the same as without those files. (#7398, #7128)
  • A default Pydantic validates holds the values strict types read from its JSON text - With --strict-types bytes, datetime, date, time or a strict Decimal, a field whose type names a model and whose default holds the text or number of a JSON document was written Field(, validate_default=True). Pydantic validates that default as Python input, where strict mode refuses the JSON value, so every instance that left the field out failed. The default is now written as the values Pydantic reads from the JSON default: bytes for a strict bytes, datetime_module.date.fromisoformat(...) and the like for an RFC 3339 date, time or datetime, Decimal(...) for a strict Decimal, through root models, objects, lists, sets, tuples and mappings. validate_default stays, so Pydantic still validates the value; text that is no RFC 3339 date or time, a value under a union of several types, bytes under a configured base class the generator cannot read and an object key the field is not written to read are left as written, so Pydantic reports them as before. Only outputs that failed at every construction without the field change; model_json_schema() shows the default as Pydantic serializes the converted value. (#7420, #7380)
  • Generated dataclass clients decode boolean and number enums inside a union - Experimental: cli-option.generate-client. In a union, the dataclasses.dataclass client codec read an enum's JSON kinds from its string and integer values alone, so a boolean or float enum decoded to the raw value and accepted values outside the enum. It now reads the kind of every value: false of enum: [false] decodes to the member and true is refused, as in Pydantic clients. A union of an open number or boolean enum and a plain number or boolean is now refused at generation, as open string and integer enums already were. (#7394, #7014)
  • Client field arguments keep the None of a nullable field - Experimental: cli-option.generate-client. Field arguments (--client-body-arguments both) and the other client and server plans now type a field with the None its model accepts where the schema admits null, also when the null sits on the field rather than in its type: a nullable map with patternProperties or propertyNames, and OpenAPI 3.0 nullable: true references, maps and arrays. labels: {type: [object, 'null'], patternProperties: ...} now gives labels: dict[str, str] | None where it gave dict[str, str]. A union of several part or payload types writes None once, last. (#7394, #7348)
  • Helper selectors read the null a field's own type accepts beside nullable: false - Experimental: cli-option.generate-client. A helper selector of a generated client read no null for a field declared nullable: false whose own type accepts null (allOf: [{$ref: MaybeText}], MaybeText nullable), except through a type alias, so the result depended on --use-type-alias. The models accept null in both forms, so the selector now reads it in both, and a root model's null counts like an alias's: a cursor over such a field needs a {kind: null} end condition with and without --use-type-alias. (#7394, #7115)
  • Generated dataclass and TypedDict clients read a nullable discriminated union by its own discriminator - Experimental: cli-option.generate-client. A property, array item or map value typed as a discriminated union or null (anyOf: [{$ref: D}, {type: 'null'}] with D a oneOf with a discriminator) stopped generation of dataclasses.dataclass and typing.TypedDict clients with 'needs a declared discriminator'. The codec now reads each model by the discriminator of the union it comes from, as it already did for D alone; several such unions join their declarations when they share the property. (#7394, #7303)
  • --input-model keeps the Python type of an unserializable field in every held class - A field JSON Schema cannot express, such as a Callable, kept its Python type (callback: Callable[[int], int]) only in a Pydantic model; in a dataclass, TypedDict, Pydantic dataclass or RootModel that the model holds it became str, which refused every valid value, and with --field-include-all-keys the id() of a schema reached the output as x-python-unserializable, a different number on every run. The field now keeps its type, found by the class the schema generation recorded for the definition, so two same-named classes keep their own fields. Class and field names stay. (#7433, #6885)
  • --input-model reuse imports the class a definition comes from - With --input-model-ref-strategy reuse-all or reuse-foreign, a field whose type is one class (item: Item of shop.Item) was typed by another class of that name that the model's fields also name, such as type[legacy.Item] or a nested Legacy.Item (item: legacy.Item), which refused every valid value. It is now typed by its own class (from shop import Item), also for a dataclass or TypedDict input and for the fields of a parent model; this is the output of 0.75.0. Every imported name keeps the class it named in 0.100.0 (here Item is shop.Item and Item1 is legacy.Item), so from <generated module> import Item is unchanged. Class and field names stay; schema-valid documents that were refused now validate. Code that passed an object of the other class (a legacy.Item) to such a field, against the schema, is now refused. (#7390, #6883)
  • A map key names the root type of its RootModel members - A map key that is a union (propertyNames anyOf or oneOf) whose members are all RootModels, a one-member wrapper of a RootModel included, was written with the RootModel class, which Pydantic cannot use as a dict key, so every key the union accepts raised TypeError. The members are now written as their root types, as a key that names the RootModel alone is; the class itself stays. A union key with a member that is no RootModel (a str, a constr call, an enum, Any) keeps the RootModel class unless --use-root-types-for-mixed-union-map-keys is set. (#7434)
  • Discriminated variants whose tag also admits null - A union that writes discriminator= over a variant whose tag field admits None is written without it, as Pydantic reads no such tag and the module failed to import (#7102); a null in the variant's enum is no tag, so it takes the enum's values instead of its schema name or, inline, the internal path marker (#7357), and an inline msgspec variant of several values takes them in its tag field and stays untagged. Variant classes keep their names, fields and the null their schema admits. (#7405, #7102, #7357)

API/CLI Changes

  • Public names for --read-allof-parents-as-their-models and --read-set-item-fields-in-class-order - The options add their config fields; nothing is removed or changed. (#7400)
  • Public name of the AsyncAPI JSON Schema media types lists application/schema - parser.asyncapi.JSON_SCHEMA_FORMATS gains the bare application/schema media type; the models are written as before. (#7389, #6937)
  • A check or JSON run reads a custom formatter's relative paths where the output lies - --check and --output-format json build the custom formatter in the directory of the real output, as the run that writes does, so a relative path of --custom-formatters-kwargs is found; they built it in a staging directory, where it was not. (#7398, #6945)
  • A Pydantic v2 model warns for the config keys it leaves out of model_config - A key of the config entry of --extra-template-data that pydantic_v2.BaseModel does not write, such as validate_assignment, was dropped without a message; the generation now warns and names the keys the model writes. The output is unchanged. (#7398, #7001)
  • A directory input skips hidden files that are not text - A hidden file of a directory input (a name or a directory below the input that starts with a dot) whose first bytes hold a NUL byte, such as the .DS_Store file Finder writes, is no longer read as a schema, so generation no longer stops with Invalid file format; a hidden file that reads as text stays an input. (#7398, #7128)
  • A stdout run with a repaired d...
Read more

0.100.0

Choose a tag to compare

@github-actions github-actions released this 22 Nov 06:18
75a2ac3

Breaking Changes

Code Generation Changes

  • Generated clients and servers now include None in container items built from several schemas - This affects the experimental --generate-client and --generate-server options. Argument and parameter types for an array or map whose items are several schemas now include None inside the container when the item union admits null. This covers prefixItems, the OpenAPI 3.0 items-array form such as items: [{type: string}, {type: integer, nullable: true}], and msgspec pattern maps. It matches what the generated models have written since 0.89.0. For example, prefixItems: [{type: string}, {type: 'null'}] with items: {type: string} now gives the client method argument, the FastAPI endpoint parameter and the generated service Protocol parameter the type list[str | None], where it was list[str]. Service implementations written against the old, narrower parameter types may no longer match the regenerated Protocol under a type checker, and code that reads these parameters must handle None items. The wire format is unchanged (#7305)

What's Changed

Read more

0.99.0

Choose a tag to compare

@github-actions github-actions released this 20 Nov 07:07
0ed4e7c

Breaking Changes

Code Generation Changes

  • Generated AsyncAPI clients now follow references into other loaded documents (experimental --generate-client) - With --generate-client and AsyncAPI input, the generator now reads a channel, operation, message, trait, binding, parameter, reply, server or security scheme declared in another loaded document at the place where the parser resolves its $ref. Channels that used to be skipped with a "references another document" warning are now generated as client helpers. An AsyncAPI 3 operation in another loaded document no longer stops the whole run with "operation ... references another document". When you regenerate such a client, it gains these helpers, and the SOCKET_N, OPERATION_N and codec_N constants in the generated protocols/_plans.py, _operations.py and _generated/model_bindings.py are renumbered. Channels that are still left out may give a different reason in their skip warning. References into a document the run did not load, and references that loop, still leave the channel out (#7137)
  • Channel servers and security requirements are now matched by where their reference leads (experimental --generate-client) - In AsyncAPI input, a channel servers entry or an operation or server security requirement whose $ref does not point straight at an entry of the root document's servers or components/securitySchemes now names the root entry that leads to the same object. Before, such an entry was ignored or the channel was skipped. So a generated channel can now get extra servers or security requirements it did not have before, or be generated where it used to be skipped (#7137)
  • Constrained union members are written as Annotated under --use-annotated - In Pydantic v2 output (pydantic_v2.BaseModel, pydantic_v2.dataclass) with --use-annotated, a union member that has its own constraints used to be written as a con*() call. This covers members in a field, a list item, a dict value or a RootModel root and generic parameter, for example the string of type: [integer, string] with a pattern, or the integer of a type list with a minimum. Such a member is now written as Annotated[<type>, Field(...)], and a Decimal multipleOf becomes MultipleOf(...). For example, code: int | constr(pattern=r'^[0-9]+$') becomes code: int | Annotated[str, Field(pattern=r'^[0-9]+$')], and RootModel[conint(ge=2) | constr(max_length=2)] becomes RootModel[Annotated[int, Field(ge=2)] | Annotated[str, Field(max_length=2)]]. The generated imports change too: constr, conint, confloat, condecimal and conbytes are no longer imported from pydantic for these members, while Annotated, Field and annotated_types.MultipleOf are added where needed. This also changes the output of the read-kubernetes-extensions presets. The models accept and reject the same values, but the generated code text and imports are different. Output without --use-annotated and with --field-constraints alone does not change (#7117)
  • Generated clients now bind the keys of a TypedDict whose bases have conflicting orders - With the experimental --generate-client option and --output-model-type typing.TypedDict, a TypedDict whose bases Python cannot order (for example E: allOf [C, D] where C: allOf [A, B] and D: allOf [B, A]) used to get an empty binding. Its codec in model_bindings.py was Model(()), decoded objects held no keys, and a body of it took no field arguments under --client-body-arguments both. Its keys are now bound in the order the models give its bases. The codec lists every field (for example Model((Field('b', 'b'), Field('a', 'a'), Field('d', 'd'), Field('c', 'c'), Field('e', 'e')))), decoded objects contain those keys in that order, and the client call that sends such a body now accepts them as field arguments. Generated clients that relied on the old empty binding behave differently (#7150)
  • AsyncAPI client payloads written as a $ref with annotation siblings are now typed by the referenced model - This affects the experimental --generate-client option with AsyncAPI input. A message payload written as a $ref beside annotations only (such as a description) is now typed and coded by the model of the schema it names, the same way an OpenAPI body is. Before, it was typed by the payload's own wrapper root model. For example, ChannelPlan[models.FeedTradePayload | models.Quote, Never] becomes ChannelPlan[models.Trade | models.Quote, Never]. Code that annotates or handles session messages as the wrapper model must switch to the referenced model (#7163)
  • AsyncAPI 2 client unions now list publish messages before subscribe messages - This affects the experimental --generate-client option with AsyncAPI 2 input. The operations of a channel are now read in the parser's order, publish then subscribe, so a stream or channel that carries both has its union written in the opposite order. For example, EventPlan[models.StatusSubscribePayload | models.StatusPublishPayload] becomes EventPlan[models.StatusPublishPayload | models.StatusSubscribePayload] (#7163)
  • Served OpenAPI document of --generate-server fastapi now resolves references the way the models do (experimental) - The _generated/openapi.json that a generated FastAPI server serves now resolves each $ref through the $id, $anchor and $dynamicAnchor names the parser registers for the models, and no longer uses its own index. Three kinds of reference used to be kept as written with the warning "The served document keeps ..., which names nothing the generation loaded". They now point to the schema the models use: a plain-name reference to an $anchor inside a namespace of definitions (such as $defs: {v1: {Label: {$anchor: label}}}) now points to /components/schemas/Pet/$defs/v1/Label; a reference through the root $id of a referenced JSON Schema document into that document (such as https://example.com/schemas/pet followed by a pointer to /$defs/Name) is now bundled as a component; and under OpenAPI 3.0, a reference by the $id of a component schema (such as https://example.com/owner.json with --no-allow-remote-refs) now resolves to that component. A plain name whose anchor is also declared by a schema beside a Reference Object (which OpenAPI ignores) now points to the anchored property the models read, not to the ignored schema. The generated models do not change, but regenerating changes the served openapi.json, so --check runs and anything that reads the served document will see different output (#7178)
  • Served OpenAPI document keeps some pointer references unresolved that it used to bundle (experimental) - With --generate-server fastapi, two kinds of JSON pointer that the models already treat as dangling references (they fall back to Any with a DanglingRefWarning) are now also left as written in the served _generated/openapi.json, and each now emits a DocumentationAnnotationWarning: a pointer below the $id of a parameter document that was first loaded through a pointer (such as /properties/size), and a pointer below the $id of a schema written inline in paths (such as /$defs/Title). The first used to be bundled. The second used to point to the inline schema's own $defs entry. Builds that treat warnings as errors will now fail on these inputs (#7178)

API/CLI Changes

  • Removed create_module_getattr from datamodel_code_generator.types and datamodel_code_generator.parser.asyncapi - Both modules used to import create_module_getattr from datamodel_code_generator.util for their old lazy __getattr__ hooks. That meant from datamodel_code_generator.types import create_module_getattr, the same import from datamodel_code_generator.parser.asyncapi, and star imports of either module all gave you that name. Those imports are gone because the modules now use the internal _lazy_exports helper, so code that reached the function through either module gets ImportError or AttributeError. Import it from datamodel_code_generator.util, where it is still available. (#7155)
  • Module dir() now lists lazily exported names - The package root, types, util, parser.avro, parser.asyncapi, parser.base, parser.jsonschema and __main__ now define __dir__, so dir() now includes lazy names such as StrictTypes, BaseModel, SafeLoader, dataclass_model, msgspec_model, TypedDictModel, Config, generate_dynamic_models and load_pyproject_config, which it used to leave out. Anything that walks dir() and reads each attribute, such as inspect.getmembers(), help() and REPL completion, now imports the modules behind those names. For example, it loads the dataclass and msgspec model modules for parser.base and the protobuf and XML Schema parsers for parser.asyncapi. Also, once a resolver name in datamodel_code_generator.reference has been read, dir() and __all__ now list it once instead of twice. (#7155)

Default Behavior Changes

  • AsyncAPI client reads channels by the configured --schema-version - This affects the experimental --generate-client option with AsyncAPI input. Channels are now read by the AsyncAPI version the models are read by: --schema-version 2.0 or 3.0 where it is given, else the document's asyncapi field. Before, only the asyncapi field was read. A run that passes a --schema-version different from the document's declared version now reads its channels by that version. This can leave channels out or make the client generation fail, for example a 3.0 document generated with --schema-version 2.0 (#7163)

Error Handling Changes

  • AsyncAPI client skip warnings change in wording, category and order - This affects the experimental --generate-client option with AsyncAPI input. A message $ref that loops is now read as the message it is written in. Its channel is reported under messages without a payload, ...
Read more

0.98.0

Choose a tag to compare

@github-actions github-actions released this 18 Nov 16:54
d31273c

Breaking Changes

Error Handling Changes

  • Client name collision errors are reported once per name and sorted (experimental --generate-client) - With the experimental --generate-client option, an explicit argument name (parameter_names or --aliases), an explicit method name (name of --client-operations) or a channel setting's resource that is taken three or more times is now reported in one E_NAME_COLLISION diagnostic instead of one per repeat. When several names collide, they are listed in sorted order instead of declaration order. Argument collisions now come after all reserved-name and --aliases diagnostics of the operation's parameters instead of being mixed in with them, and channel resource collisions come after the refusals of dotted resources. For example, The arguments of GET /items take 'b' twice; ... take 'a' twice becomes ... take 'a' twice; ... take 'b' twice. Tooling that matches the exact text, count or order of these error messages must be updated. Generated code is unchanged (#6987)
  • Reserved explicit method name taken twice no longer adds a collision error (experimental --generate-client) - An explicit client method name that is a reserved member name such as close, given to two operations of one resource, is now reported only as a reserved name. The extra The resource ... takes the name ... twice collision error is no longer emitted (#6987)
  • Generated servers stop validating dropped other members against their additionalProperties type - With the experimental --generate-server, other members that a model drops by its configuration are no longer checked against the type additionalProperties gives them. Under --extra-fields ignore, a multipart body whose other members are typed as an object now serves x=abc, where it used to answer 422 json_invalid (and model_type or dict_type for x=5). With pydantic_v2.dataclass, a URL-encoded or multipart body typed by additionalProperties: {type: integer} now serves x=abc, where it used to answer 422 int_parsing. Under --extra-fields forbid such members are still refused with 422. Separately, under --extra-fields forbid a request that leaves out a query or cookie object but carries other keys is now served with obj=None, where it used to get 422 (#7039)
  • Omitting a body field the model requires now raises TypeError before any request - This affects the experimental --generate-client feature. With --strip-default-none, calling a generated method without a field the model constructor requires (for example create_pet(id=1)) now raises TypeError: create_pet() missing required field arguments for application/json: 'tag' before any request is sent. Before, the model raised DecodeError(reason='unencodable') (#7070)
  • AsyncAPI messages without their tag, or with a null tag, are refused with different reasons - This affects the experimental --generate-client feature. With --strip-default-none, on a channel routed by an optional tag property, a received message that lacks the property is now refused as missing instead of value. A message whose tag is null, which the union decoder used to accept as the first member, is now refused with reason null (#7070)

Code Generation Changes

  • Generated client and server plans drop other-member entries for objects whose model drops extra members - With the experimental --generate-client and --generate-server, form bodies, client form and query object parameters, and multipart bodies typed by a Pydantic model or dataclass now follow the configuration the model applies, bases included. Where that configuration says extra='forbid' or 'ignore', they take no other members. 'ignore' includes a class that sets no extra, which is the default. Regenerated code no longer has additional=FieldPlan('', 'string') or the matching reserved_names=(...) in a client's form or query plans, additional=PartPlan('', 'json') and its parts= in a client's multipart body sent whole, or additional=JsonPart('', TypeAdapter(object), untyped=True) in a server's _generated/contract.py. A client call option also no longer counts the undeclared names of such an object as written by its pagination. Nothing changes under --extra-fields allow (#7039)
  • Pydantic dataclass extra-member serialization follows the applied configuration - With the experimental --generate-client or --generate-server and --output-model-type pydantic_v2.dataclass, the client codec extras_serializer, the server response dump=extras_json (with the primary status it adds) and the copied _runtime/model_codecs/pydantic_extras.py (a server's shared.py too) are now emitted only where the configuration Pydantic applies says extra='allow'. That is the dataclass's own configuration, or its first base's when it has none. A class written with --class-decorators now counts, so such a dataclass with additionalProperties: true now sends and returns its extra members: the client sends {"v":"a","foo":"b"} where it used to send {"v":"a"}. Two kinds of dataclass lose extras_serializer and dump=extras_json: one whose own configuration sets no extra (for example from --allow-population-by-field-name) under a base with additionalProperties: true, and one whose first base forbids extra members (#7039)
  • Server form field-name members follow the applied by-name configuration - With the experimental --generate-server, a form the server reads through its own adapter (multipart, or URL-encoded with pydantic_v2.dataclass) now lists the field-name FieldPlan entries only where the applied configuration sets populate_by_name or validate_by_name, with bases merged as Pydantic does. A model that turns it off over a base that sets it, or a dataclass with its own configuration under such a base, no longer lists the field names. A class written with --class-decorators now lists them (#7039)
  • Schema validators reject a boolean for a numeric const or enum value and a number for a boolean one - With the experimental --generate-schema-validators option (or --schema-validator-type pydantic-v2), a const or enum that holds a boolean, or a number equal to one (0, 1), now gets a check on the raw input. Payloads that Python's True == 1 used to let through are now rejected with Expected the JSON type of the schema constant: true for const: 1, enum: [1, 2] or enum: [1, "x"], and 1 for const: true. The check covers properties, array items, mapping values, referenced Enum classes, the consts of oneOf and anyOf branches, and root models. 1.0 for const: 1 is still accepted, and an enum that holds both, such as enum: [1, true], still accepts both. Data that the generated models accepted before may now fail validation. (#7067)
  • Generated models gain a constant-type validator base and class variable - Under --generate-schema-validators, models with such constants now declare __json_schema_constant_types__: ClassVar[tuple[tuple[object, ...], ...]] and inherit a shared helper base that adds the _validate_json_schema_constant_types model validator. A model whose only schema-validator rule is a const or enum can now subclass _JsonSchemaRuntimeValidationBase instead of plain BaseModel. When a module also needs the core or uniqueItems helper, that helper is renamed to _JsonSchemaRuntimeValidationBaseCore, and _JsonSchemaRuntimeValidationBase becomes the constant-type layer on top of it. These modules also gain import re, so the generated output and helper class names change for existing schemas. (#7067)
  • Generated client body field arguments now follow the model constructor under --strip-default-none - This affects the experimental --generate-client feature. With --strip-default-none, a property the schema leaves optional whose Pydantic model field has no default (for example tag: str | None) is now a required field argument of the call that sends the body. It is written as tag: str instead of tag: str | UNSET = UNSET, the README marks it tag (required) and its FieldArguments flag is true. An OpenAPI 3.0 nullable: true property that the model writes without a default also becomes required, and so does an optional nullable: true property with default: null in pydantic_v2.dataclass output. A property whose schema type includes null (OpenAPI 3.1 type: [string, "null"]) keeps its = None default and stays optional. In the other direction, a required property marked x-is-classvar (with --field-include-all-keys) becomes optional in pydantic_v2.BaseModel and pydantic_v2.dataclass output, because a ClassVar is not a constructor argument. Calls that left out the newly required arguments must now pass them (#7070)
  • AsyncAPI channels and SSE streams told apart by an optional tag property now route by that tag - This affects the experimental --generate-client feature. With --strip-default-none, a generated WebSocket channel whose messages are told apart by an optional constant property (kind: {const: join}) now routes received messages by that property (MessageRoute(..., tag='join') with a BodySelector discriminator) instead of decoding them as a union of the message models. Server-sent event streams under --strip-default-none --force-optional likewise route events by the body tag (BodySelector(pointer="/type")) instead of using one union codec (#7070)
  • Model field defaults are wrapped in typing.cast under --use-annotated - With --use-annotated and --output-model-type pydantic_v2.BaseModel, Pydantic validates some field defaults into a model (validate_default=True). This covers fields whose type holds a model or root model, including lists, dicts, sets and tuples of models, unions of models, scalar root models, and unions of a model with a format type such as a URL or date. Before, such a field was assigned the raw schema value, for example `flags: Annotated[Flags | Non...
Read more

0.97.0

Choose a tag to compare

@github-actions github-actions released this 17 Nov 01:21
32093bf

Breaking Changes

Error Handling Changes

  • Unmatched --type-overrides keys now emit a UserWarning - The --type-overrides option (and the type_overrides argument of the Python API and parsers) now checks every key after parsing. If any key names no generated model or field, it emits a single UserWarning such as --type-overrides: 2 keys matched no generated model or field: 'Order.itme' (did you mean 'Order.item'?), 'Ordr' (did you mean 'Order'?). Where a close key exists, the warning suggests it, for example the class name a schema name was renamed to (ItemModel.price for Item.price). The generated code does not change. Previously such keys were silently ignored, so runs that passed with no warnings can now print a warning on stderr. Callers that turn warnings into errors (-W error, pytest filterwarnings = error) will now get an error. To fix it, correct or remove the keys the warning names. With --diff-against, the warning covers only the current input, not the baseline. (#6838)
  • Server and client targets raise Error for a preset that does not fit the target Python version (experimental) - When generate() runs with the experimental generate_server or generate_client target and its preset does not match target_python_version, it now raises datamodel_code_generator.Error with the same message a model-only run gives. Before, it raised datamodel_code_generator.preset.PresetError, which is not a subclass of Error, so code that caught PresetError around a target run no longer catches it and should catch datamodel_code_generator.Error instead. The command line is unchanged. (#6864)
  • A new UserWarning is emitted when an option is turned off but another option turns it back on - --use-annotated turns on --field-constraints, --use-type-alias-type turns on --use-type-alias and --intersect-combined-schema-keywords turns on --intersect-allof-keywords, including when a preset sets the first option or the output model type does (for example msgspec turning on --use-annotated). Previously, a run that turned the second option off kept it on without saying so. This happened with an argument such as --no-intersect-allof-keywords, with false in pyproject.toml, or with False passed to generate(). Now such a run emits a UserWarning that names both options, says where the implying option came from, and explains how to turn both off. The generated code does not change, but callers that turn warnings into errors (for example -W error or pytest filterwarnings = error) now get an error for these combinations. The warning is not shown under --disable-warnings. It is also not emitted for a pyproject.toml value that a --preset argument replaces, for use_type_alias passed to generate(), or for values of a config returned by load_pyproject_config() (#6889)
  • A dataclass instance passed to --input-model now fails with a clear error - Pointing --input-model at an instance of a dataclass, for example module:default_user, now reports 'default_user' is not a supported type. Supported: dict, Pydantic v2 BaseModel, dataclass, TypedDict. In 0.96.0 it crashed with an AttributeError; pass the class (module:User) instead.
  • New SchemaResourceRefWarning before fetching a document whose own $id ends with an empty fragment - When a JSON Schema or OpenAPI document declares an $id ending with an empty fragment and a $ref in that same document names that URI or a pointer under it, the generator still fetches the document from that URL as in 0.96.0, but now warns first with a SchemaResourceRefWarning. The warning names the document, the URL and the written $id, and suggests --read-ids-with-empty-fragment. The generated output does not change. Callers that turn warnings into errors (for example -W error or warnings.simplefilter("error")) now get an error instead of a successful run. To avoid it, pass --read-ids-with-empty-fragment or write the $id without the trailing fragment marker (#6898)
  • New UserWarning when a command-line argument turns off an option that pyproject.toml turned on - With use-annotated = true and field-constraints = false in pyproject.toml, passing --no-use-annotated turns --use-annotated off. --field-constraints stays on, because the command line applies the pyproject.toml values, and the option they imply, before the arguments. That was already the 0.96.0 behaviour, but such a run now emits a UserWarning: --field-constraints was turned off but stays on: use-annotated = true in pyproject.toml turns it on, which --no-use-annotated does not undo; use-annotated = false in pyproject.toml or --read-implied-options-from-merged-values turns it off. The generated output does not change. Callers that turn warnings into errors, for example with -W error or pytest filterwarnings = error, now fail. To avoid the warning, set use-annotated = false in pyproject.toml instead of passing --no-use-annotated, or pass --disable-warnings. You can also opt in to the new --read-implied-options-from-merged-values, under which the argument also turns --field-constraints off, which changes the output to conint. (#6911)
  • AsyncAPI client skip warnings reworded - In the experimental generated AsyncAPI client, a channel skipped because an AsyncAPI 2 operation's own HTTP binding declares query or headers now warns the query schema of its HTTP binding has no model (or the headers equivalent) instead of the HTTP binding of an AsyncAPI 2 operation on it declares query, which no model types. A query or headers object is now reported as is not an object of properties only when the models type it as something other than an object, so some skip warnings disappear or change their text and tooling that matches these warning messages needs updating (#6958)

Code Generation Changes

  • Generated AsyncAPI clients skip channels whose payload format generation does not read - With the experimental --generate-client, a channel is now left out with a message_content_types warning in two cases. The first is an AsyncAPI 2 message trait that gives a schemaFormat the parser does not read, such as application/schema;version=draft-07. The client used to accept any application/schema or application/vnd.aai.asyncapi spelling through a regex, and now codes only formats whose kind is asyncapi, jsonschema or openapi. The second is a message contentType that is not a valid media type but ends in +json, such as x+json, which is no longer treated as JSON. These channels used to be generated with a JSON codec, so their helpers are missing after regenerating. Write the format as the AsyncAPI specification lists it (application/schema+json;version=draft-07) and the content type as a real media type (application/x+json). (#6939)
  • Generated AsyncAPI clients now generate channels that were skipped or failed - With the experimental --generate-client, some channels are now generated instead of being skipped as message_content_types. These are channels whose payload gives its schemaFormat in another case or with spaces (application/SCHEMA+JSON;version=draft-07, application/schema+json ; version=draft-07), in an OpenAPI format (application/vnd.oai.openapi;version=3.0.0), or in such a spelling through an AsyncAPI 2 trait. Also, a payload written {schema: ...} without a schemaFormat now binds the model generated for its schema. Generation used to fail with The use has no generated native type when it was the channel's only message, and the channel was skipped as several_messages when it sat beside another JSON message. A regenerated client gains helpers for these channels and loses their skip warnings. The numbered internal names after them shift, for example SOCKET_6 becomes SOCKET_7 in protocols/_plans.py and codec_13 becomes codec_14 in _generated/model_bindings.py, so snapshot tests and committed generated clients change. (#6939)
  • Generated AsyncAPI clients carry binary-string JSON messages as raw bytes - This affects the experimental --generate-client feature. A WebSocket channel message with a JSON content type whose payload is a binary string (type: string, format: binary) is now typed, sent and received as raw bytes in binary frames. Before, the payload's model encoded and decoded it in text frames. Code that passes or expects the model type for such channels must switch to bytes. Server-sent event channels still decode the event data with the model (#6957)
  • Generated AsyncAPI clients type some octet-stream and text messages as str instead of bytes - This affects the experimental --generate-client feature. Two kinds of message are now typed str and sent and received as UTF-8 text frames, where they were bytes in binary frames: an application/octet-stream message whose payload is an enum of strings, and a text message whose binary-string payload the models type as str (for example with --type-mappings binary=string). The send and receive types of the generated channel helpers change for these channels (#6957)
  • AsyncAPI client handshake parameters now follow the generated models - With the experimental --generate-client on AsyncAPI documents, the query and header parameters of a channel's connect(...) or open(...) are now the fields of the models generated for its binding's query and headers objects, including inherited ones, and are required only where the models require them. Under --force-optional every handshake parameter is now optional, where it used to be required whenever the binding object required it. A parameter written as a $ref now takes the description of the schema it names in the generated helper. Some channels that used to be skipped with a warning are now generated and add new helpers to the client: channels whose query or headers object uses allOf, has keywords beside its pr...
Read more

0.96.0

Choose a tag to compare

@github-actions github-actions released this 13 Nov 20:51
2c0111e

Breaking Changes

Code Generation Changes

  • Generated client methods return raw bodies for itemSchema stream responses - For an OpenAPI 3.2 response media of text/event-stream or a JSON Lines or NDJSON type (application/jsonl, application/jsonlines, application/ndjson, application/x-jsonl, application/x-jsonlines, application/x-ndjson) whose schema is only an itemSchema, the generated client no longer binds the model of the item schema's array projection to the operation's response. The operation method, its with_response view and its result type alias now read the whole body raw: str for an event stream (a text branch) and bytes for JSON Lines or NDJSON (a binary branch). For example, WatchEventsResponse becomes str, and a JSON plus JSON Lines response becomes models.ExcerptGetResponse | bytes. Code that relied on the old result type must parse the raw body or use the new stream helper that regenerated clients now get at client.protocols.<resource>.<method>, which yields typed items (#6767)
  • Generated client stream helpers now type items as the model the itemSchema references - In generated Python clients, SSE, JSON Lines and NDJSON stream helpers whose itemSchema is a bare $ref now use the referenced model, for example EventStream[models.LogEntry], AsyncEventStream[models.Event] and EventPlan[models.LogEntry]. Before, they used the duplicate ItemSchema or ItemSchemaModel model generated at the item schema location. The codecs in _generated/model_bindings.py change to match. With Pydantic v2 output, decoded stream items are now instances of the referenced model, for example models.LogEntry instead of models.ItemSchemaModel, and validation error messages name that model. With dataclasses output, only the type annotations change. Code that annotates, isinstance-checks or pattern-matches stream items against models.ItemSchema or models.ItemSchemaModel has to switch to the referenced model (#6771)
  • Const, enum and allOf branches no longer take object keywords under --read-object-keywords-by-type - With --read-object-keywords-by-type, which the standard and practical 20261112 presets also turn on, the check for an anyOf or oneOf branch that admits no object now looks at more than a declared type or a $ref to such a schema. It also counts const, enum, nested allOf, anyOf and oneOf parts, false schemas, and the full schema a $ref names together with the keywords beside it. Branches found this way are now read without the sibling properties, patternProperties, additionalProperties, propertyNames, unevaluatedProperties, required, minProperties and maxProperties. For example, an anyOf of a const branch, an enum branch and an object branch next to properties and required used to generate a single model field Owner | None and now generates a union like Literal['none'] | Owner | Owner1 | None. That adds new enum classes and can shift model names: the former Owner model becomes Owner1. Under --generate-schema-validators these sites also become unions instead of one validated object model. Output without the option is unchanged (#6777)
  • Regex patterns containing quotes are written differently in Pydantic v2 output - With pydantic_v2.BaseModel and pydantic_v2.dataclass output, a pattern containing a single quote used to be written as a single-quoted raw literal with the quote escaped by a backslash, for example constr(pattern=r'^it\'s$'). Because raw literals keep backslashes, the runtime pattern string had an extra backslash before the quote. The generator now picks a quote character the pattern does not use, so this becomes constr(pattern=r"^it's$"). A pattern containing both quote characters is now written as a plain (non-raw) literal, for example '^a-z\'"+$' instead of r'^a-z\'"+$', and backslashes in such patterns are doubled. A pattern that already holds a backslash before a quote changes only in source text: "^don\\'t$" becomes r"^don\'t$". This affects string field patterns, propertyNames key patterns, and StringConstraints written under --field-constraints or --use-annotated. Python's re matches the same values, so validation does not change. However, the pattern stored in constr or StringConstraints, and the pattern that model_json_schema() publishes (for example in FastAPI OpenAPI docs), no longer has the extra backslash. The generated source text for these fields also changes, so snapshot tests or committed generated code will show differences after regenerating (#6790)

Error Handling Changes

  • Helper names that collide with derived item stream helpers are now refused - When an OpenAPI 3.2 document has responses that stream an itemSchema, generation now derives a stream helper named <resource>.<method> for each such operation. A helper in the protocols helper file whose name contains a derived name, or is contained in one (for example a declared helper named default beside the derived default.watch_events), now fails generation with an E_NAME_COLLISION config diagnostic reported under the client protocols option. The same helper file used to generate. To fix it, rename the declared helper (#6767)
  • Deprecation and migration notices now name the code that called datamodel-code-generator instead of a module inside the package - Notices emitted through the central deprecation registry used to be attributed to a frame inside datamodel_code_generator, picked by a fixed stacklevel at each call site. They are now attributed to the outermost frame outside the package. In the Python API that is the user module that called generate() or another API. In the CLI it is the console script, or the runpy frame for python -m. This covers the optional-dependency notices (Genson, Jinja2, Black/isort, Pydantic runtime minimum), the default formatters notice, the deprecated --validation, --parent-scoped-naming and --allow-extra-fields notices, the remote $ref default notice, the OpenAPI nullable and JSON Schema array items notices, PythonVersion.has_type_alias and the other registry notices. As a result, each notice reports a different filename, line number and module. Filters that matched these notices by module="datamodel_code_generator" no longer suppress them, whether set in warnings.filterwarnings, -W, PYTHONWARNINGS or pytest filterwarnings. To silence them, filter by category and message, or target the calling module, for example warnings.filterwarnings("ignore", category=FutureWarning, module="mypackage.models"). Python's default filters show DeprecationWarning only when it is attributed to __main__. A script that calls the API directly may therefore now show registry notices of category DeprecationWarning that were hidden before (#6793)

What's Changed

New Contributors

Full Changelog: 0.95.0...0.96.0

0.95.0

Choose a tag to compare

@github-actions github-actions released this 12 Nov 08:56
57f7893

Breaking Changes

Code Generation Changes

  • Required nullable parameters in generated FastAPI servers are now typed without None - A required query, path, header or cookie parameter can have a nullable schema, such as OpenAPI 3.0 nullable: true or 3.1 type: [string, "null"], and not be described by content. For such a parameter, the generated router endpoint now writes the plain type, for example Annotated[str, Query(alias='q')] instead of Annotated[str | None, Query(alias='q')]. The generated service Protocol method now takes it as q: str instead of q: str | None. This also covers a nullable type that the target reads through a root model or alias. Optional parameters and parameters with a content media type keep | None. Implementations that still declare X | None keep type-checking, because such a parameter can never receive None. After regenerating, though, code that calls service methods with None for these parameters, or that relies on the old signatures, gets type errors. FastAPI's own OpenAPI document, served with source_openapi=False, also no longer marks these parameters nullable. (#6737)
  • Schema validators no longer read references mapped by --external-ref-mapping - With --generate-schema-validators, a $ref that --external-ref-mapping maps to an imported class is no longer loaded when runtime validation rules are collected. Before, if the mapped document could be read, its rules went into the generated validators. These were minProperties/maxProperties and scoped object rules such as patternProperties reached through allOf/anyOf/oneOf items, and the uniqueItems rules of union branches. Now the mapped reference adds no rules, and it is treated as possibly accepting both object and array data. Generated models can therefore lose validation checks they had before, for example the uniqueItems check on an array branch next to a mapped object branch, and accept data they used to reject. Schemas that used to fail because the mapped document was missing or refused by --strict-refs now generate. (#6762)

Default Behavior Changes

  • Dynamic model generation no longer formats generated code by default - generate_dynamic_models() and generate_dynamic_module() now skip formatting when none of formatters, custom_formatters or the config's preset selects formatters. Before, they formatted the code with Black and isort, as generate() does. Black and isort are no longer imported in that case, and the "Default formatters will change to builtin" FutureWarning is no longer emitted. Presets that do not set formatters, such as standard-py313-20260619, now also give unformatted code. Formatting stripped spaces and tabs from the ends of lines in class docstrings. So with use_schema_description=True, a schema description whose lines end with spaces or tabs (for example a Markdown hard break) now keeps that trailing whitespace in the class __doc__ and in the description that Pydantic's model_json_schema() reports. Set formatters (for example formatters=[Formatter.BUILTIN]) to bring back formatting and the stripped docstrings. generate() and the CLI are unchanged. (#6750)
  • New FutureWarning when custom templates are used - Generation with a custom template directory (--custom-template-dir, custom-template-dir in pyproject.toml, or custom_template_dir in the generate() config) now emits the dependency.jinja2-optional FutureWarning "Jinja2 will become optional. Declare the jinja2 extra for --custom-template-dir; see --help." It is shown once per CLI invocation and on each generate() call. Python shows FutureWarning by default, so this is new stderr output for existing users. Setups that turn warnings into errors (-W error, PYTHONWARNINGS=error, pytest filterwarnings = error) now fail until the warning is filtered. Jinja2 is still a required dependency; declare the new jinja2 extra to prepare for it becoming optional. (#6755)
  • New FutureWarning when generating from raw data input - Generating from JSON, YAML, CSV or dict sample data (--input-file-type json, yaml or csv, or generate() with a dict) now emits the dependency.genson-optional FutureWarning "Genson will become optional. Declare the genson extra for JSON, YAML, CSV and dict input; see --help." Schema inputs such as JSON Schema and OpenAPI do not warn. Setups that turn warnings into errors now fail for these inputs until the warning is filtered. Genson is still a required dependency; declare the new genson extra to prepare for it becoming optional. (#6755)

Error Handling Changes

  • Experimental --untrusted-input now refuses deeply nested or very large schemas - With the experimental --untrusted-input option (untrusted_input=True in generate() and in the GenerateConfig of the dynamic API), a schema whose objects and arrays nest more than 100 levels deep, or that holds more than 2,000,000 objects and arrays, now stops generation with an error. A YAML alias counts each time it is used. The check runs before the document is parsed: on each input document, on converted sources, and in generate_dynamic_models before the schema is hashed for the cache. These schemas could generate under --untrusted-input in 0.94.0. The error names the limit and how deep or large the schema is. To process such a schema, flatten or split it, or generate without --untrusted-input if the schema is trusted. Behaviour without the option does not change. (#6752)

What's Changed

Full Changelog: 0.94.0...0.95.0

0.94.0

Choose a tag to compare

@github-actions github-actions released this 12 Nov 00:58
36070df

Breaking Changes

Code Generation Changes

  • Generated client methods no longer accept None for required nullable parameters - For a required query, path, header or cookie parameter serialized by its style rather than by a content media type, whose schema is nullable (for example type: string, nullable: true with --strict-nullable, or type: [string, "null"] in OpenAPI 3.1, directly or through a root model or type alias), the generated client now types the keyword argument without None, such as q: str instead of q: str | None and ids: list[int] instead of a nullable list[int] for a root model of a nullable array; the fields of the Operation0Arguments-style TypedDict used by the unpack signature style change the same way. Code that passes None or an optional-typed value to these arguments now fails type checking after regeneration, while parameters sent through content, optional parameters, and nullable items inside arrays such as list[str | None] keep None (#6726)

What's Changed

Full Changelog: 0.93.0...0.94.0

0.93.0

Choose a tag to compare

@github-actions github-actions released this 11 Nov 07:50
d300d81

Breaking Changes

Error Handling Changes

  • The deprecated --validation option is now rejected when used with --no-allow-remote-refs - Passing --validation together with --no-allow-remote-refs (or validation=True with allow_remote_refs=False in the Python API) when parsing OpenAPI input used to run the prance validator, which fetched remote $ref URLs even though remote refs were turned off. The parser now raises an Error instead: "--validation is refused under --no-allow-remote-refs: its validator resolves the $ref of the document by itself and fetches the URLs that --no-allow-remote-refs blocks." The command exits with an error and no code is generated. This works the same way as the existing refusal of --validation under --untrusted-input. If you use both options, drop --validation (it is deprecated) or stop passing --no-allow-remote-refs. (#6688)

Python Version Changes

  • Dropped support for running on Python 3.10 - The package now declares requires-python = ">=3.11". The Python 3.10 classifier is gone, and so is the tomli dependency that was only installed below Python 3.11. datamodel-code-generator can no longer be installed or run on Python 3.10, and pip and uv will keep Python 3.10 environments on the 0.92.x release. This completes the deprecation announced in 0.84.0: the dependency.python-310-runtime FutureWarning is no longer emitted, and its registry entry, shown by --list-deprecations, now records removal in 0.93.0. Only the interpreter running the generator is affected. The default target is still Python 3.10, and code generated for Python 3.10, with or without --target-python-version 3.10, is unchanged. Projects still on Python 3.10 can keep generating code by running the tool on a newer Python, for example uvx datamodel-code-generator --target-python-version 3.10 ... (#6701)

What's Changed

Full Changelog: 0.92.0...0.93.0