Skip to content

Pydantic Converter

PydanticConverter builds runtime BaseModel classes directly from a validated YadsSpec. It honors include/exclude filters, column overrides, and lets you name or configure the generated class so request/response payloads stay aligned with the canonical schema.

import yads
from yads.converters import PydanticConverter, PydanticConverterConfig
import json

spec = yads.from_yaml("docs/src/specs/submissions.yaml")

converter = PydanticConverter(PydanticConverterConfig(mode="coerce"))
Submission = converter.convert(spec)
print(json.dumps(Submission.model_json_schema(), indent=2))
{
  "properties": {
    "submission_id": {
      "maximum": 9223372036854775807,
      "minimum": -9223372036854775808,
      "title": "Submission Id",
      "type": "integer",
      "yads": {
        "primary_key": true
      }
    },
    "completion_percent": {
      "anyOf": [
        {
          "type": "number"
        },
        {
          "pattern": "^(?!^[-+.]*$)[+-]?0*(?:\\d{0,3}|(?=[\\d.]{1,6}0*$)\\d{0,3}\\.\\d{0,2}0*$)",
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": 0.0,
      "title": "Completion Percent"
    },
    "time_taken_seconds": {
      "anyOf": [
        {
          "maximum": 2147483647,
          "minimum": -2147483648,
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "title": "Time Taken Seconds"
    },
    "submitted_at": {
      "anyOf": [
        {
          "format": "date-time",
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "title": "Submitted At"
    }
  },
  "required": [
    "submission_id",
    "time_taken_seconds",
    "submitted_at"
  ],
  "title": "prod_assessments_submissions",
  "type": "object"
}

Info

Install one of the supported versions of Pydantic to use this converter with uv add 'yads[pydantic]'

PydanticConverter

Bases: BaseConverter[Any]

Convert a yads YadsSpec into a Pydantic BaseModel class.

The converter maps each yads column to a Pydantic field and assembles a BaseModel class. Complex types such as arrays, structs, and maps are recursively converted to their Pydantic equivalents.

Notes
  • Complex types (Array, Struct, Map) are converted to their Pydantic equivalents using nested models and typing constructs.
  • Geometry and Geography types are not supported and raise UnsupportedFeatureError unless in coerce mode.
Source code in src/yads/converters/pydantic_converter.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
class PydanticConverter(BaseConverter[Any]):
    """Convert a yads `YadsSpec` into a Pydantic `BaseModel` class.

    The converter maps each yads column to a Pydantic field and assembles a
    `BaseModel` class. Complex types such as arrays, structs, and maps are
    recursively converted to their Pydantic equivalents.

    Notes:
        - Complex types (Array, Struct, Map) are converted to their Pydantic
          equivalents using nested models and typing constructs.
        - Geometry and Geography types are not supported and raise
          `UnsupportedFeatureError` unless in coerce mode.
    """

    def __init__(self, config: PydanticConverterConfig | None = None) -> None:
        """Initialize the PydanticConverter.

        Args:
            config: Configuration object. If None, uses default PydanticConverterConfig.
        """
        self.config: PydanticConverterConfig = config or PydanticConverterConfig()
        super().__init__(self.config)

    @requires_dependency("pydantic", min_version="2.0.0", import_name="pydantic")
    def convert(
        self,
        spec: yspec.YadsSpec,
        *,
        mode: Literal["raise", "coerce"] | None = None,
    ) -> Type[BaseModel]:
        """Convert a yads `YadsSpec` into a Pydantic `BaseModel` class.

        Args:
            spec: The yads spec as a `YadsSpec` object.
            mode: Optional conversion mode override for this call. When not
                provided, the converter's configured mode is used. If provided:
                - "raise": Raise on any unsupported features.
                - "coerce": Apply adjustments to produce a valid model and emit warnings.

        Returns:
            A Pydantic `BaseModel` class with fields mapped from the spec columns.
        """
        from pydantic import create_model, ConfigDict  # type: ignore[import-untyped]

        model_name: str = self.config.model_name or spec.name.replace(".", "_")
        model_config: dict[str, Any] = self.config.model_config or {}

        fields: dict[str, Any] = {}
        with self.conversion_context(mode=mode):
            self._validate_column_filters(spec)
            for col in self._filter_columns(spec):
                with self.conversion_context(field=col.name):
                    field_type, field_info = self._convert_field_with_overrides(col)

                    # Pydantic expects (annotation, FieldInfo) for dynamic models
                    fields[col.name] = (field_type, field_info)

        config_dict: ConfigDict | None = None
        if model_config:
            config_dict = cast(ConfigDict, model_config)

        model = create_model(
            model_name,
            __config__=config_dict,
            **fields,
        )

        return model

    # %% ---- Type conversion ---------------------------------------------------------
    @singledispatchmethod
    def _convert_type(self, yads_type: ytypes.YadsType) -> tuple[Any, dict[str, Any]]:
        # Fallback for currently unsupported:
        # - Geometry
        # - Geography
        # - Tensor
        fallback_type: Any = self.raise_or_coerce(yads_type)
        return fallback_type, {}

    @_convert_type.register(ytypes.String)
    def _(self, yads_type: ytypes.String) -> tuple[Any, dict[str, Any]]:
        params: dict[str, Any] = {}
        if yads_type.length:
            params["max_length"] = yads_type.length
        return str, params

    @_convert_type.register(ytypes.Integer)
    def _(self, yads_type: ytypes.Integer) -> tuple[Any, dict[str, Any]]:
        params: dict[str, Any] = {}
        if yads_type.bits:
            if yads_type.signed:
                min_val = -(2 ** (yads_type.bits - 1))
                max_val = 2 ** (yads_type.bits - 1) - 1
            else:  # unsigned
                min_val = 0
                max_val = 2**yads_type.bits - 1
            params["ge"] = min_val
            params["le"] = max_val
        else:
            # Unsigned without bit width: enforce non-negative only.
            if not yads_type.signed:
                params["ge"] = 0
        return int, params

    @_convert_type.register(ytypes.Float)
    def _(self, yads_type: ytypes.Float) -> tuple[Any, dict[str, Any]]:
        # Python's float is typically 64-bit; emit warning when a narrower
        # bit-width is requested, since precision cannot be enforced.
        if yads_type.bits is not None and yads_type.bits != 64:
            # Use raise_or_coerce for consistent warning/error handling
            self.raise_or_coerce(
                coerce_type=float,
                error_msg=(
                    f"Float(bits={yads_type.bits}) cannot be represented exactly"
                    f" in Pydantic; Python float is 64-bit for '{self._field_context}'."
                ),
            )
        return float, {}

    @_convert_type.register(ytypes.Decimal)
    def _(self, yads_type: ytypes.Decimal) -> tuple[Any, dict[str, Any]]:
        params: dict[str, Any] = {}
        if yads_type.precision is not None and self._supports_decimal_constraints():
            params["max_digits"] = yads_type.precision
            params["decimal_places"] = yads_type.scale
        elif yads_type.precision is not None and not self._supports_decimal_constraints():
            # Decimal constraints not supported in this Pydantic version
            # Use raise_or_coerce to emit warning, but continue with PythonDecimal
            self.raise_or_coerce(
                coerce_type=PythonDecimal,
                error_msg=(
                    f"Decimal precision and scale constraints require Pydantic >= 2.8.0"
                    f" for '{self._field_context}'. "
                    f"Found version {get_installed_version('pydantic') or 'unknown'}."
                ),
            )
        return PythonDecimal, params

    @_convert_type.register(ytypes.Boolean)
    def _(self, yads_type: ytypes.Boolean) -> tuple[Any, dict[str, Any]]:
        return bool, {}

    @_convert_type.register(ytypes.Binary)
    def _(self, yads_type: ytypes.Binary) -> tuple[Any, dict[str, Any]]:
        params: dict[str, Any] = {}
        if yads_type.length:
            params["min_length"] = yads_type.length
            params["max_length"] = yads_type.length
        return bytes, params

    @_convert_type.register(ytypes.Date)
    def _(self, yads_type: ytypes.Date) -> tuple[Any, dict[str, Any]]:
        # Ignore bit-width parameter
        if yads_type.bits is not None:
            self.raise_or_coerce(
                coerce_type=date,
                error_msg=(
                    f"{yads_type} cannot be represented in Pydantic; "
                    f"bits constraint will be lost for '{self._field_context}'."
                ),
            )
        return date, {}

    @_convert_type.register(ytypes.Time)
    def _(self, yads_type: ytypes.Time) -> tuple[Any, dict[str, Any]]:
        # Ignore bit-width parameter
        # Ignore unit parameter
        if yads_type.bits is not None or yads_type.unit is not None:
            self.raise_or_coerce(
                coerce_type=time,
                error_msg=(
                    f"{yads_type} cannot be represented in Pydantic; "
                    f"bits and/or unit constraints will be lost for '{self._field_context}'."
                ),
            )
        return time, {}

    @_convert_type.register(ytypes.Timestamp)
    def _(self, yads_type: ytypes.Timestamp) -> tuple[Any, dict[str, Any]]:
        # Ignore unit parameter
        if yads_type.unit is not None:
            self.raise_or_coerce(
                coerce_type=datetime,
                error_msg=(
                    f"{yads_type} cannot be represented in Pydantic; "
                    f"unit constraint will be lost for '{self._field_context}'."
                ),
            )
        return datetime, {}

    @_convert_type.register(ytypes.TimestampTZ)
    def _(self, yads_type: ytypes.TimestampTZ) -> tuple[Any, dict[str, Any]]:
        # Ignore unit parameter and timezone parameter
        if yads_type.unit is not None:
            self.raise_or_coerce(
                coerce_type=datetime,
                error_msg=(
                    f"{yads_type} cannot be represented in Pydantic; "
                    f"unit and/or tz constraints will be lost for '{self._field_context}'."
                ),
            )
        return datetime, {}

    @_convert_type.register(ytypes.TimestampLTZ)
    def _(self, yads_type: ytypes.TimestampLTZ) -> tuple[Any, dict[str, Any]]:
        # Ignore unit parameter
        if yads_type.unit is not None:
            self.raise_or_coerce(
                coerce_type=datetime,
                error_msg=(
                    f"{yads_type} cannot be represented in Pydantic; "
                    f"unit constraint will be lost for '{self._field_context}'."
                ),
            )
        return datetime, {}

    @_convert_type.register(ytypes.TimestampNTZ)
    def _(self, yads_type: ytypes.TimestampNTZ) -> tuple[Any, dict[str, Any]]:
        # Ignore unit parameter
        if yads_type.unit is not None:
            self.raise_or_coerce(
                coerce_type=datetime,
                error_msg=(
                    f"{yads_type} cannot be represented in Pydantic; "
                    f"unit constraint will be lost for '{self._field_context}'."
                ),
            )
        return datetime, {}

    @_convert_type.register(ytypes.Duration)
    def _(self, yads_type: ytypes.Duration) -> tuple[Any, dict[str, Any]]:
        # Ignore unit parameter
        if yads_type.unit is not None:
            self.raise_or_coerce(
                coerce_type=timedelta,
                error_msg=(
                    f"{yads_type} cannot be represented in Pydantic; "
                    f"unit constraint will be lost for '{self._field_context}'."
                ),
            )
        return timedelta, {}

    @_convert_type.register(ytypes.Interval)
    def _(self, yads_type: ytypes.Interval) -> tuple[Any, dict[str, Any]]:
        from pydantic import Field, create_model  # type: ignore[import-untyped]

        # Represent as a structured Month-Day-Nano interval, matching PyArrow's
        # month_day_nano_interval layout: (months, days, nanoseconds)
        interval_model_name = self._nested_model_name("MonthDayNanoInterval")
        months_field = (int, Field(default=...))
        days_field = (int, Field(default=...))
        nanos_field = (int, Field(default=...))
        interval_model = create_model(
            interval_model_name,
            months=months_field,
            days=days_field,
            nanoseconds=nanos_field,
        )
        return interval_model, {}

    @_convert_type.register(ytypes.Array)
    def _(self, yads_type: ytypes.Array) -> tuple[Any, dict[str, Any]]:
        element_type, _ = self._convert_type(yads_type.element)
        list_type = list[element_type]  # type: ignore[valid-type]

        params: dict[str, Any] = {}
        if yads_type.size:
            params["min_length"] = yads_type.size
            params["max_length"] = yads_type.size

        return list_type, params

    @_convert_type.register(ytypes.Struct)
    def _(self, yads_type: ytypes.Struct) -> tuple[Any, dict[str, Any]]:
        from pydantic import create_model  # type: ignore[import-untyped]

        # Create nested model for struct
        nested_fields: dict[str, tuple[Any, FieldInfo]] = {}
        for yads_field in yads_type.fields:
            with self.conversion_context(field=yads_field.name):
                field_type, field_info = self._convert_field(yads_field)
                nested_fields[yads_field.name] = (field_type, field_info)

        # Create nested model class
        struct_model_name = self._nested_model_name(yads_type.__class__.__name__)
        # Preserve FieldInfo for nested fields
        nested_kwargs: dict[str, Any] = {
            key: value for key, value in nested_fields.items()
        }
        nested_model: Any = create_model(struct_model_name, **nested_kwargs)

        return nested_model, {}

    @_convert_type.register(ytypes.Map)
    def _(self, yads_type: ytypes.Map) -> tuple[Any, dict[str, Any]]:
        key_type, _ = self._convert_type(yads_type.key)
        value_type, _ = self._convert_type(yads_type.value)

        dict_type = dict[key_type, value_type]  # type: ignore[valid-type]

        if yads_type.keys_sorted:
            self.raise_or_coerce(
                coerce_type=dict_type,
                error_msg=(
                    f"{yads_type} cannot be represented in Pydantic; "
                    f"keys_sorted parameter will be lost for '{self._field_context}'."
                ),
            )
        return dict_type, {}

    @_convert_type.register(ytypes.JSON)
    def _(self, yads_type: ytypes.JSON) -> tuple[Any, dict[str, Any]]:
        # Map to dict for JSON data
        return dict, {}

    @_convert_type.register(ytypes.UUID)
    def _(self, yads_type: ytypes.UUID) -> tuple[Any, dict[str, Any]]:
        return PythonUUID, {}

    @_convert_type.register(ytypes.Void)
    def _(self, yads_type: ytypes.Void) -> tuple[Any, dict[str, Any]]:
        # Represent a NULL/VOID value
        return type(None), {"default": None}

    @_convert_type.register(ytypes.Variant)
    def _(self, yads_type: ytypes.Variant) -> tuple[Any, dict[str, Any]]:
        return Any, {}

    def _convert_field(self, field: yspec.Field) -> tuple[Any, FieldInfo]:
        from pydantic import Field  # type: ignore[import-untyped]

        field_type, field_params = self._convert_type(field.type)

        if field.is_nullable:
            field_type = Optional[field_type]

        if field.description:
            field_params["description"] = field.description

        json_schema_extra: dict[str, Any] = {}
        if field.metadata:
            json_schema_extra["metadata"] = field.metadata

        for constraint in field.constraints:
            field_params, json_schema_extra = self._apply_constraint(
                constraint, field_params, json_schema_extra
            )

        if json_schema_extra:
            # Wrap in "yads" key to avoid collisions
            field_params["json_schema_extra"] = {"yads": json_schema_extra}

        if "default" not in field_params:
            field_params["default"] = ...

        field_info: FieldInfo = Field(**field_params)  # type: ignore[assignment]
        return field_type, field_info

    def _convert_field_default(self, field: yspec.Field) -> tuple[Any, FieldInfo]:
        return self._convert_field(field)

    def _apply_column_override(self, field: yspec.Field) -> tuple[Any, FieldInfo]:
        from pydantic.fields import FieldInfo  # type: ignore[import-untyped]

        result = self.config.column_overrides[field.name](field, self)
        if not (isinstance(result, tuple) and len(result) == 2):  # pyright: ignore[reportUnnecessaryIsInstance]
            raise UnsupportedFeatureError(
                "Pydantic column override must return (annotation, FieldInfo)."
            )
        annotation, field_info = result
        if not isinstance(field_info, FieldInfo):  # pyright: ignore[reportUnnecessaryIsInstance]
            raise UnsupportedFeatureError(
                "Pydantic column override second element must be a FieldInfo."
            )
        return annotation, field_info

    # %% ---- Constraint conversion ---------------------------------------------------
    @singledispatchmethod
    def _apply_constraint(
        self,
        constraint: ColumnConstraint,
        field_params: dict[str, Any],
        json_schema_extra: dict[str, Any],
    ) -> tuple[dict[str, Any], dict[str, Any]]:
        # Fallback for unknown constraints does nothing
        return field_params, json_schema_extra

    @_apply_constraint.register(NotNullConstraint)
    def _(
        self,
        constraint: NotNullConstraint,
        field_params: dict[str, Any],
        json_schema_extra: dict[str, Any],
    ) -> tuple[dict[str, Any], dict[str, Any]]:
        # Nullability is handled by default=...
        return field_params, json_schema_extra

    @_apply_constraint.register(PrimaryKeyConstraint)
    def _(
        self,
        constraint: PrimaryKeyConstraint,
        field_params: dict[str, Any],
        json_schema_extra: dict[str, Any],
    ) -> tuple[dict[str, Any], dict[str, Any]]:
        # Capture primary key metadata in schema extras
        json_schema_extra["primary_key"] = True
        return field_params, json_schema_extra

    @_apply_constraint.register(DefaultConstraint)
    def _(
        self,
        constraint: DefaultConstraint,
        field_params: dict[str, Any],
        json_schema_extra: dict[str, Any],
    ) -> tuple[dict[str, Any], dict[str, Any]]:
        field_params["default"] = constraint.value
        return field_params, json_schema_extra

    @_apply_constraint.register(ForeignKeyConstraint)
    def _(
        self,
        constraint: ForeignKeyConstraint,
        field_params: dict[str, Any],
        json_schema_extra: dict[str, Any],
    ) -> tuple[dict[str, Any], dict[str, Any]]:
        # Capture foreign key metadata in schema extras
        fk_metadata: dict[str, Any] = {
            "table": constraint.references.table,
        }
        if constraint.references.columns:
            fk_metadata["columns"] = list(constraint.references.columns)
        if constraint.name:
            fk_metadata["name"] = constraint.name
        json_schema_extra["foreign_key"] = fk_metadata
        return field_params, json_schema_extra

    @_apply_constraint.register(IdentityConstraint)
    def _(
        self,
        constraint: IdentityConstraint,
        field_params: dict[str, Any],
        json_schema_extra: dict[str, Any],
    ) -> tuple[dict[str, Any], dict[str, Any]]:
        # Capture identity/auto-increment metadata in schema extras
        identity_metadata: dict[str, Any] = {"always": constraint.always}
        if constraint.start is not None:
            identity_metadata["start"] = constraint.start
        if constraint.increment is not None:
            identity_metadata["increment"] = constraint.increment
        json_schema_extra["identity"] = identity_metadata
        return field_params, json_schema_extra

    # %% ---- Helpers -----------------------------------------------------------------
    @staticmethod
    @lru_cache(maxsize=1)
    def _supports_decimal_constraints() -> bool:
        """Check if the installed Pydantic version supports Decimal constraints.

        Decimal max_digits and decimal_places constraints were introduced in
        Pydantic 2.8.0.
        """
        pydantic_version = get_installed_version("pydantic")
        if pydantic_version is None:
            return False
        return meets_min_version(pydantic_version, "2.8.0")

    def _nested_model_name(self, suffix: str) -> str:
        base = self.config.model_name or "Model"
        return f"{base}_{suffix}"

__init__(config=None)

Initialize the PydanticConverter.

Parameters:

Name Type Description Default
config PydanticConverterConfig | None

Configuration object. If None, uses default PydanticConverterConfig.

None
Source code in src/yads/converters/pydantic_converter.py
118
119
120
121
122
123
124
125
def __init__(self, config: PydanticConverterConfig | None = None) -> None:
    """Initialize the PydanticConverter.

    Args:
        config: Configuration object. If None, uses default PydanticConverterConfig.
    """
    self.config: PydanticConverterConfig = config or PydanticConverterConfig()
    super().__init__(self.config)

conversion_context(*, mode=None, field=None)

Temporarily set conversion mode and field context.

This context manager centralizes handling of converter state used for warnings and coercions, ensuring that values are restored afterwards.

Parameters:

Name Type Description Default
mode Literal['raise', 'coerce'] | None

Optional override for the current conversion mode.

None
field str | None

Optional field name for contextual warnings.

None
Source code in src/yads/converters/base.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
@contextmanager
def conversion_context(
    self,
    *,
    mode: Literal["raise", "coerce"] | None = None,
    field: str | None = None,
) -> Generator[None, None, None]:
    """Temporarily set conversion mode and field context.

    This context manager centralizes handling of converter state used for
    warnings and coercions, ensuring that values are restored afterwards.

    Args:
        mode: Optional override for the current conversion mode.
        field: Optional field name for contextual warnings.
    """
    # Snapshot current state
    previous_config = self.config
    previous_field = self._current_field_name

    try:
        if mode is not None:
            if mode not in ("raise", "coerce"):
                raise ConverterConfigError("mode must be one of 'raise' or 'coerce'.")
            self.config = replace(self.config, mode=mode)
        if field is not None:
            self._current_field_name = field
        yield
    finally:
        # Restore prior state
        self.config = previous_config
        self._current_field_name = previous_field

convert(spec, *, mode=None)

Convert a yads YadsSpec into a Pydantic BaseModel class.

Parameters:

Name Type Description Default
spec YadsSpec

The yads spec as a YadsSpec object.

required
mode Literal['raise', 'coerce'] | None

Optional conversion mode override for this call. When not provided, the converter's configured mode is used. If provided: - "raise": Raise on any unsupported features. - "coerce": Apply adjustments to produce a valid model and emit warnings.

None

Returns:

Type Description
Type[BaseModel]

A Pydantic BaseModel class with fields mapped from the spec columns.

Source code in src/yads/converters/pydantic_converter.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
@requires_dependency("pydantic", min_version="2.0.0", import_name="pydantic")
def convert(
    self,
    spec: yspec.YadsSpec,
    *,
    mode: Literal["raise", "coerce"] | None = None,
) -> Type[BaseModel]:
    """Convert a yads `YadsSpec` into a Pydantic `BaseModel` class.

    Args:
        spec: The yads spec as a `YadsSpec` object.
        mode: Optional conversion mode override for this call. When not
            provided, the converter's configured mode is used. If provided:
            - "raise": Raise on any unsupported features.
            - "coerce": Apply adjustments to produce a valid model and emit warnings.

    Returns:
        A Pydantic `BaseModel` class with fields mapped from the spec columns.
    """
    from pydantic import create_model, ConfigDict  # type: ignore[import-untyped]

    model_name: str = self.config.model_name or spec.name.replace(".", "_")
    model_config: dict[str, Any] = self.config.model_config or {}

    fields: dict[str, Any] = {}
    with self.conversion_context(mode=mode):
        self._validate_column_filters(spec)
        for col in self._filter_columns(spec):
            with self.conversion_context(field=col.name):
                field_type, field_info = self._convert_field_with_overrides(col)

                # Pydantic expects (annotation, FieldInfo) for dynamic models
                fields[col.name] = (field_type, field_info)

    config_dict: ConfigDict | None = None
    if model_config:
        config_dict = cast(ConfigDict, model_config)

    model = create_model(
        model_name,
        __config__=config_dict,
        **fields,
    )

    return model

raise_or_coerce(yads_type=None, *, coerce_type=None, error_msg=None)

Handle raise or coerce mode for unsupported type features.

This public method provides a consistent way to handle unsupported types based on the converter's mode. It can be used within converters and in custom column override functions.

The method uses the template method pattern with several hook methods that subclasses can override to customize behavior.

Hook that subclasses can override
  • _format_type_for_display: Customize how types appear in warnings
  • _emit_warning: Customize warning emission
  • _get_fallback_type: Customize fallback type resolution
  • _generate_error_message: Customize error message generation

Parameters:

Name Type Description Default
yads_type Any | None

The yads type that is not supported. Can be None if error_msg is explicitly provided.

None
coerce_type Any | None

The type to coerce to in coerce mode. If None, uses the converter's configured fallback type.

None
error_msg str | None

Custom error message. If None, uses a default message based on the converter class name and yads_type. When providing a custom error_msg, yads_type can be None.

None

Returns:

Type Description
T

The coerced type in coerce mode.

Raises:

Type Description
UnsupportedFeatureError

In raise mode when the feature is not supported, or in coerce mode when fallback_type is None.

ValueError

If both yads_type and error_msg are None.

Source code in src/yads/converters/base.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
def raise_or_coerce(
    self,
    yads_type: Any | None = None,
    *,
    coerce_type: Any | None = None,
    error_msg: str | None = None,
) -> T:
    """Handle raise or coerce mode for unsupported type features.

    This public method provides a consistent way to handle unsupported types
    based on the converter's mode. It can be used within converters and in
    custom column override functions.

    The method uses the template method pattern with several hook methods
    that subclasses can override to customize behavior.

    Hook that subclasses can override:
        - `_format_type_for_display`: Customize how types appear in warnings
        - `_emit_warning`: Customize warning emission
        - `_get_fallback_type`: Customize fallback type resolution
        - `_generate_error_message`: Customize error message generation

    Args:
        yads_type: The yads type that is not supported. Can be None if
            error_msg is explicitly provided.
        coerce_type: The type to coerce to in coerce mode. If None, uses
            the converter's configured fallback type.
        error_msg: Custom error message. If None, uses a default message
            based on the converter class name and yads_type. When providing
            a custom error_msg, yads_type can be None.

    Returns:
        The coerced type in coerce mode.

    Raises:
        UnsupportedFeatureError: In raise mode when the feature is not supported,
            or in coerce mode when fallback_type is None.
        ValueError: If both yads_type and error_msg are None.
    """
    # Resolve error message once
    if error_msg is None:
        if yads_type is None:
            raise ValueError(
                "Either yads_type or error_msg must be provided to raise_or_coerce"
            )
        error_msg = self._generate_error_message(yads_type)

    # Resolve coerce_type (fallback to config if not provided)
    if coerce_type is None:
        try:
            coerce_type = self._get_fallback_type()
        except ValueError:
            # fallback_type is None - must raise even in coerce mode
            if self.config.mode == "coerce":
                error_msg = f"{error_msg} Specify a fallback_type to enable coercion of unsupported types."
            raise UnsupportedFeatureError(error_msg)

    # Handle based on mode
    if self.config.mode == "coerce":
        display_type = self._format_type_for_display(coerce_type)
        warning_msg = f"{error_msg} The data type will be coerced to {display_type}."
        self._emit_warning(warning_msg)
        return coerce_type
    else:
        raise UnsupportedFeatureError(error_msg)

PydanticConverterConfig dataclass

Bases: BaseConverterConfig[Any]

Configuration for PydanticConverter.

Parameters:

Name Type Description Default
mode Literal['raise', 'coerce']

Conversion mode. One of "raise" or "coerce". Inherited from BaseConverterConfig. Defaults to "coerce".

'coerce'
ignore_columns frozenset[str]

Column names to exclude from conversion. Inherited from BaseConverterConfig. Defaults to empty.

_empty_frozenset_str()
include_columns frozenset[str] | None

If provided, only these columns are included. Inherited from BaseConverterConfig. Defaults to None.

None
column_overrides Mapping[str, Callable[[Field, PydanticConverter], tuple[Any, FieldInfo]]]

Mapping of column name to a callable that returns a custom Pydantic field conversion. Inherited from BaseConverterConfig. Defaults to empty mapping.

(lambda: MappingProxyType({}))()
model_name str | None

Custom name for the generated model class. If None, uses the spec name. Defaults to None.

None
model_config dict[str, Any] | None

Dictionary of Pydantic model configuration options. Defaults to empty dict.

None
fallback_type type | None

Python type to use for unsupported types in coerce mode. Must be one of: str, dict, bytes, or None. Defaults to None.

None
Source code in src/yads/converters/pydantic_converter.py
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
@dataclass(frozen=True)
class PydanticConverterConfig(BaseConverterConfig[Any]):
    """Configuration for PydanticConverter.

    Args:
        mode: Conversion mode. One of "raise" or "coerce". Inherited from
            BaseConverterConfig. Defaults to "coerce".
        ignore_columns: Column names to exclude from conversion. Inherited from
            BaseConverterConfig. Defaults to empty.
        include_columns: If provided, only these columns are included. Inherited
            from BaseConverterConfig. Defaults to None.
        column_overrides: Mapping of column name to a callable that returns a
            custom Pydantic field conversion. Inherited from BaseConverterConfig.
            Defaults to empty mapping.
        model_name: Custom name for the generated model class. If None, uses
            the spec name. Defaults to None.
        model_config: Dictionary of Pydantic model configuration options.
            Defaults to empty dict.
        fallback_type: Python type to use for unsupported types in coerce mode.
            Must be one of: str, dict, bytes, or None. Defaults to None.
    """

    model_name: str | None = None
    model_config: dict[str, Any] | None = None
    fallback_type: type | None = None
    column_overrides: Mapping[
        str,
        Callable[[yspec.Field, PydanticConverter], tuple[Any, FieldInfo]],
    ] = field(default_factory=lambda: MappingProxyType({}))

    def __post_init__(self) -> None:
        """Validate configuration parameters."""
        super().__post_init__()

        # Validate fallback_type if provided
        if self.fallback_type is not None:
            valid_fallback_types = {str, dict, bytes}
            if self.fallback_type not in valid_fallback_types:
                raise UnsupportedFeatureError(
                    f"fallback_type must be one of: str, dict, bytes, or None. Got: {self.fallback_type}"
                )

__post_init__()

Validate configuration parameters.

Source code in src/yads/converters/pydantic_converter.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def __post_init__(self) -> None:
    """Validate configuration parameters."""
    super().__post_init__()

    # Validate fallback_type if provided
    if self.fallback_type is not None:
        valid_fallback_types = {str, dict, bytes}
        if self.fallback_type not in valid_fallback_types:
            raise UnsupportedFeatureError(
                f"fallback_type must be one of: str, dict, bytes, or None. Got: {self.fallback_type}"
            )