Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added
- `datacontract export pydantic-model`: a `default` custom property on an optional property becomes the field default (#1700)
- `datacontract import pydantic-model`: a scalar field default becomes a `default` custom property (#1700)

## [1.2.3] - 2026-10-05

### Added
Expand Down
8 changes: 6 additions & 2 deletions datacontract/export/pydantic_exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,14 @@ def field_value(prop: SchemaProperty) -> ast.expr | None:
# Draft-04 JSON Schema had boolean exclusive bounds, and an empty pattern does not import back.
if isinstance(value, (int, float, str)) and not isinstance(value, bool) and value != "":
keywords.append(ast.keyword(arg=keyword, value=ast.Constant(value)))
# A `default` custom property becomes the field default; only optional fields have one.
default = next((cp.value for cp in prop.customProperties or [] if cp.property == "default"), None)
if not isinstance(default, (bool, int, float, str)):
default = None
if not keywords:
return None if prop.required else ast.Constant(None)
return None if prop.required else ast.Constant(default)
if not prop.required:
keywords.insert(0, ast.keyword(arg="default", value=ast.Constant(None)))
keywords.insert(0, ast.keyword(arg="default", value=ast.Constant(default)))
return ast.Call(
func=ast.Attribute(value=ast.Name(id="pydantic", ctx=ast.Load()), attr="Field", ctx=ast.Load()),
args=[],
Expand Down
7 changes: 7 additions & 0 deletions datacontract/imports/pydantic_importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ class _FieldInfo:
def __init__(self) -> None:
self.description: Optional[str] = None
self.has_default: bool = False
self.default: Any = None
self.examples: Optional[List[Any]] = None
self.constraints: Dict[str, Any] = {}

Expand All @@ -186,6 +187,7 @@ def _parse_field_call(call: ast.Call, info: _FieldInfo) -> None:
elif keyword.arg == "default":
if not (isinstance(keyword.value, ast.Constant) and keyword.value.value is Ellipsis):
info.has_default = True
info.default = _literal_value(keyword.value)
elif keyword.arg == "default_factory":
info.has_default = True
elif keyword.arg in _CONSTRAINT_KEYWORDS:
Expand All @@ -211,6 +213,7 @@ def _field_info(assign: ast.AnnAssign, metadata: List[ast.expr]) -> _FieldInfo:
_parse_field_call(assign.value, info)
elif not (isinstance(assign.value, ast.Constant) and assign.value.value is Ellipsis):
info.has_default = True
info.default = _literal_value(assign.value)

return info

Expand Down Expand Up @@ -328,11 +331,15 @@ def _to_property(
resolved = _resolved_kwargs(annotation, index, depth)
resolved.update(info.constraints)

# A scalar default is kept as a `default` custom property, which the exporter writes back as the field default.
custom_properties = {"default": info.default} if isinstance(info.default, (bool, int, float, str)) else None

return create_property(
name=name,
description=info.description or docstring,
required=not optional and not info.has_default,
examples=info.examples,
custom_properties=custom_properties,
**resolved,
)

Expand Down
15 changes: 14 additions & 1 deletion docs/docs/exports/pydantic-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,20 @@ class Line_items(pydantic.BaseModel):

## Defaults and constraints

Fields that are not `required` are typed `typing.Optional[...]` and default to `None`.
Fields that are not `required` are typed `typing.Optional[...]` and default to `None`, or to the value of a `default` custom property on the property:

```yaml
- name: tarif_dynamique
logicalType: string
required: false
customProperties:
- property: default
value: NON
```

```python
tarif_dynamique: typing.Optional[str] = 'NON'
```

`logicalTypeOptions` become `pydantic.Field` constraints, so the generated model rejects what `datacontract test` would flag:

Expand Down
5 changes: 3 additions & 2 deletions docs/docs/imports/pydantic-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ executing any of its code.

Module-level models become schema objects, except those used as the type of another
model's field: those are inlined as nested objects. `Field(...)` constraints become
`logicalTypeOptions`, and `Literal` types and `Enum` classes become an `invalidValues`
quality rule listing the valid values.
`logicalTypeOptions`, a scalar field default becomes a `default` custom property, and
`Literal` types and `Enum` classes become an `invalidValues` quality rule listing the
valid values.

{/* AUTOGENERATED EXAMPLE: do not edit by hand; regenerate with the update script. */}

Expand Down
3 changes: 3 additions & 0 deletions tests/fixtures/pydantic-model/expected/models.odcs.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,9 @@ schema:
physicalType: bool
logicalType: boolean
required: false
customProperties:
- property: default
value: false
- name: payload
physicalType: bytes
logicalType: array
Expand Down
64 changes: 63 additions & 1 deletion tests/test_export_pydantic.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@

import pydantic
import pytest
from open_data_contract_standard.model import Description, OpenDataContractStandard, SchemaObject, SchemaProperty
from open_data_contract_standard.model import (
CustomProperty,
Description,
OpenDataContractStandard,
SchemaObject,
SchemaProperty,
)

import datacontract.export.pydantic_exporter as conv

Expand Down Expand Up @@ -359,3 +365,59 @@ def test_generated_model_enforces_the_constraints():
orders(total=1, label="a,,b")
with pytest.raises(pydantic.ValidationError):
orders(total=-1)


def test_default_custom_property_becomes_the_field_default():
schema = SchemaObject(
name="Test",
properties=[
SchemaProperty(
name="f",
logicalType="string",
logicalTypeOptions={"pattern": "^(OUI|NON)$"},
customProperties=[CustomProperty(property="default", value="NON")],
),
SchemaProperty(
name="g", logicalType="boolean", customProperties=[CustomProperty(property="default", value=False)]
),
],
)
ast_class = conv.generate_model_class("Test", schema)
assert (
ast.unparse(ast_class)
== dedent(
"""
class Test(pydantic.BaseModel):
f: typing.Optional[str] = pydantic.Field(default='NON', pattern='^(OUI|NON)$')
g: typing.Optional[bool] = False
"""
).strip()
)


def test_default_is_ignored_on_a_required_field_or_when_not_a_scalar():
schema = SchemaObject(
name="Test",
properties=[
SchemaProperty(
name="f",
logicalType="string",
required=True,
customProperties=[CustomProperty(property="default", value="x")],
),
SchemaProperty(
name="g", logicalType="string", customProperties=[CustomProperty(property="default", value=["a", "b"])]
),
],
)
ast_class = conv.generate_model_class("Test", schema)
assert (
ast.unparse(ast_class)
== dedent(
"""
class Test(pydantic.BaseModel):
f: str
g: typing.Optional[str] = None
"""
).strip()
)
9 changes: 9 additions & 0 deletions tests/test_import_pydantic_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,12 @@ def test_an_unknown_annotation_is_imported_as_string_with_a_warning(tmp_path, ca

assert result.schema_[0].properties[0].logicalType == "string"
assert "will be imported as string:\npayload (SomeCustomType)\n" in caplog.text


def test_a_scalar_default_becomes_a_default_custom_property():
result = DataContract.import_from_source("pydantic-model", models_file_path)
properties = properties_of(result.schema_[0])

assert [(cp.property, cp.value) for cp in properties["is_gift"].customProperties] == [("default", False)]
assert properties["note"].customProperties is None # str | None = None
assert properties["tags"].customProperties is None # list[str] = []
1 change: 1 addition & 0 deletions tests/test_roundtrip_pydantic_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def shape(properties):
bool(prop.required),
prop.description,
{key: value for key, value in (prop.logicalTypeOptions or {}).items() if key in CONSTRAINTS},
[cp.value for cp in prop.customProperties or [] if cp.property == "default"],
shape(prop.properties or []),
shape([prop.items] if prop.items else []),
)
Expand Down
Loading