Skip to content

PyArrow Converter

PyArrowConverter turns a validated YadsSpec into a pyarrow.Schema and respects the same include/exclude filters available on every converter. Use it directly or through yads.to_pyarrow whenever you need a deterministic schema object for downstream Arrow consumers. The snippet below loads the shared submissions spec from YAML and prints the resulting schema.

import yads
from yads.converters import PyArrowConverter, PyArrowConverterConfig

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

converter = PyArrowConverter(PyArrowConverterConfig(mode="coerce"))
schema = converter.convert(spec)
print(schema)
submission_id: int64 not null
completion_percent: decimal128(5, 2)
time_taken_seconds: int32
submitted_at: timestamp[ns, tz=UTC]

Info

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

PyArrowConverter

Bases: BaseConverter[Any]

Convert a yads YadsSpec into a pyarrow.Schema.

The converter maps each yads column to a pyarrow.Field and assembles a pyarrow.Schema. Complex types such as arrays, structs, and maps are recursively converted.

In "raise" mode, incompatible parameters raise UnsupportedFeatureError. In "coerce" mode, the converter attempts to coerce to a compatible target (e.g., promote decimal to 256-bit or time to 64-bit when units require it). If a logical type is unsupported by PyArrow, it is mapped to a canonical fallback pa.binary().

Notes
  • Arrow strings are variable-length; any String.length hint is ignored in the resulting Arrow schema.
  • Geometry, Geography, and Variant are not supported and raise UnsupportedFeatureError unless in coerce mode.
Source code in src/yads/converters/pyarrow_converter.py
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
class PyArrowConverter(BaseConverter[Any]):
    """Convert a yads `YadsSpec` into a `pyarrow.Schema`.

    The converter maps each yads column to a `pyarrow.Field` and assembles a
    `pyarrow.Schema`. Complex types such as arrays, structs, and maps are
    recursively converted.

    In "raise" mode, incompatible parameters raise `UnsupportedFeatureError`.
    In "coerce" mode, the converter attempts to coerce to a compatible target
    (e.g., promote decimal to 256-bit or time to 64-bit when units require it).
    If a logical type is unsupported by PyArrow, it is mapped to a canonical
    fallback `pa.binary()`.

    Notes:
        - Arrow strings are variable-length; any `String.length` hint is
          ignored in the resulting Arrow schema.
        - `Geometry`, `Geography`, and `Variant` are not supported and raise
          `UnsupportedFeatureError` unless in coerce mode.
    """

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

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

    @requires_dependency("pyarrow", import_name="pyarrow")
    def convert(
        self,
        spec: yspec.YadsSpec,
        *,
        mode: Literal["raise", "coerce"] | None = None,
    ) -> Any:
        """Convert a yads `YadsSpec` into a `pyarrow.Schema`.

        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 schema and emit warnings.

        Returns:
            A `pyarrow.Schema` with fields mapped from the spec columns.
        """
        import pyarrow as pa  # type: ignore[import-untyped]

        fields: list[pa.Field] = []
        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_result = self._convert_field_with_overrides(col)
                    fields.append(field_result)
        schema_metadata = self._coerce_metadata(spec.metadata) if spec.metadata else None
        return pa.schema(fields, metadata=schema_metadata)

    # %% ---- Type conversion ---------------------------------------------------------
    # Time unit constraints for Arrow
    _TIME32_UNITS: frozenset[str] = frozenset({"s", "ms"})
    _TIME64_UNITS: frozenset[str] = frozenset({"us", "ns"})

    @singledispatchmethod
    def _convert_type(self, yads_type: ytypes.YadsType) -> pa.DataType:
        # Fallback for currently unsupported:
        # - Geometry
        # - Geography
        # - Variant
        return self.raise_or_coerce(yads_type)

    @_convert_type.register(ytypes.String)
    def _(self, yads_type: ytypes.String) -> pa.DataType:
        import pyarrow as pa  # type: ignore[import-untyped]

        # Arrow strings are variable-length. Optionally use large_string.
        if yads_type.length is not None:
            self.raise_or_coerce(
                coerce_type=pa.large_string()
                if self.config.use_large_string
                else pa.string(),
                error_msg=(
                    f"{yads_type} cannot be represented in PyArrow; "
                    f"length constraint will be lost for '{self._field_context}'."
                ),
            )
        return pa.large_string() if self.config.use_large_string else pa.string()

    @_convert_type.register(ytypes.Integer)
    def _(self, yads_type: ytypes.Integer) -> pa.DataType:
        import pyarrow as pa  # type: ignore[import-untyped]

        bits = yads_type.bits or 32
        signed_map = {
            8: pa.int8(),
            16: pa.int16(),
            32: pa.int32(),
            64: pa.int64(),
        }
        unsigned_map = {
            8: pa.uint8(),
            16: pa.uint16(),
            32: pa.uint32(),
            64: pa.uint64(),
        }
        mapping = signed_map if yads_type.signed else unsigned_map
        try:
            return mapping[bits]
        except KeyError as e:
            raise UnsupportedFeatureError(
                f"Unsupported Integer bits: {bits}. Expected 8/16/32/64"
                f" for '{self._field_context}'."
            ) from e

    @_convert_type.register(ytypes.Float)
    def _(self, yads_type: ytypes.Float) -> pa.DataType:
        import pyarrow as pa  # type: ignore[import-untyped]

        bits = yads_type.bits or 32
        mapping = {16: pa.float16(), 32: pa.float32(), 64: pa.float64()}
        try:
            return mapping[bits]
        except KeyError as e:
            raise UnsupportedFeatureError(
                f"Unsupported Float bits: {bits}. Expected 16/32/64"
                f" for '{self._field_context}'."
            ) from e

    @_convert_type.register(ytypes.Decimal)
    def _(self, yads_type: ytypes.Decimal) -> pa.DataType:
        import pyarrow as pa  # type: ignore[import-untyped]

        # Determine width function first, considering precision constraints.
        precision = yads_type.precision or 38
        scale = yads_type.scale or 18
        bits = yads_type.bits

        def build_decimal(width_bits: int) -> pa.DataType:
            if width_bits == 128:
                return pa.decimal128(precision, scale)
            if width_bits == 256:
                return pa.decimal256(precision, scale)
            raise UnsupportedFeatureError(
                f"Unsupported Decimal bits: {width_bits}. Expected 128/256"
                f" for '{self._field_context}'."
            )

        if bits is None:
            # Choose width based on precision threshold.
            return build_decimal(256 if precision > 38 else 128)

        if bits == 128 and precision > 38:
            return self.raise_or_coerce(
                coerce_type=build_decimal(256),
                error_msg=(
                    "precision > 38 is incompatible with Decimal(bits=128)"
                    f" for '{self._field_context}'."
                ),
            )
        return build_decimal(bits)

    @_convert_type.register(ytypes.Boolean)
    def _(self, yads_type: ytypes.Boolean) -> pa.DataType:
        import pyarrow as pa  # type: ignore[import-untyped]

        return pa.bool_()

    @_convert_type.register(ytypes.Binary)
    def _(self, yads_type: ytypes.Binary) -> pa.DataType:
        import pyarrow as pa  # type: ignore[import-untyped]

        if yads_type.length is not None:
            return pa.binary(yads_type.length)
        return pa.large_binary() if self.config.use_large_binary else pa.binary()

    @_convert_type.register(ytypes.Date)
    def _(self, yads_type: ytypes.Date) -> pa.DataType:
        import pyarrow as pa  # type: ignore[import-untyped]

        bits = yads_type.bits or 32
        mapping = {32: pa.date32(), 64: pa.date64()}
        try:
            return mapping[bits]
        except KeyError as e:
            raise UnsupportedFeatureError(
                f"Unsupported Date bits: {bits}. Expected 32/64"
                f" for '{self._field_context}'."
            ) from e

    @_convert_type.register(ytypes.Time)
    def _(self, yads_type: ytypes.Time) -> pa.DataType:
        import pyarrow as pa  # type: ignore[import-untyped]

        unit = self._to_pa_time_unit(yads_type.unit)
        bits = yads_type.bits

        if bits is None:
            # Infer from unit
            if unit in self._TIME32_UNITS:
                return pa.time32(unit)
            return pa.time64(unit)

        if bits == 32:
            if unit not in self._TIME32_UNITS:
                return self.raise_or_coerce(
                    coerce_type=pa.time64(unit),
                    error_msg=(
                        "time32 supports only 's' or 'ms' units"
                        f" (got '{unit}') for '{self._field_context}'."
                    ),
                )
            return pa.time32(unit)
        elif bits == 64:
            if unit not in self._TIME64_UNITS:
                # Promote coarse units to 32 if asked for 64 but unit is s/ms
                return self.raise_or_coerce(
                    coerce_type=pa.time32(unit),
                    error_msg=(
                        "time64 supports only 'us' or 'ns' units"
                        f" (got '{unit}') for '{self._field_context}'."
                    ),
                )
            return pa.time64(unit)
        raise UnsupportedFeatureError(
            f"Unsupported Time bits: {bits}. Expected 32/64 for '{self._field_context}'."
        )

    @_convert_type.register(ytypes.Timestamp)
    def _(self, yads_type: ytypes.Timestamp) -> pa.DataType:
        return self._build_timestamp(yads_type.unit, tz=None)

    @_convert_type.register(ytypes.TimestampTZ)
    def _(self, yads_type: ytypes.TimestampTZ) -> pa.DataType:
        return self._build_timestamp(yads_type.unit, tz=yads_type.tz)

    @_convert_type.register(ytypes.TimestampLTZ)
    def _(self, yads_type: ytypes.TimestampLTZ) -> pa.DataType:
        return self._build_timestamp(yads_type.unit, tz=None)

    @_convert_type.register(ytypes.TimestampNTZ)
    def _(self, yads_type: ytypes.TimestampNTZ) -> pa.DataType:
        return self._build_timestamp(yads_type.unit, tz=None)

    @_convert_type.register(ytypes.Duration)
    def _(self, yads_type: ytypes.Duration) -> pa.DataType:
        import pyarrow as pa  # type: ignore[import-untyped]

        unit = self._to_pa_time_unit(yads_type.unit)
        return pa.duration(unit)

    @_convert_type.register(ytypes.Interval)
    def _(self, yads_type: ytypes.Interval) -> pa.DataType:
        import pyarrow as pa  # type: ignore[import-untyped]

        return pa.month_day_nano_interval()

    @_convert_type.register(ytypes.Array)
    def _(self, yads_type: ytypes.Array) -> pa.DataType:
        import pyarrow as pa  # type: ignore[import-untyped]

        value_type = self._convert_type(yads_type.element)
        if yads_type.size is not None:
            return pa.list_(value_type, list_size=yads_type.size)
        return (
            pa.large_list(value_type)
            if self.config.use_large_list
            else pa.list_(value_type)
        )

    @_convert_type.register(ytypes.Struct)
    def _(self, yads_type: ytypes.Struct) -> pa.DataType:
        import pyarrow as pa  # type: ignore[import-untyped]

        fields = []
        for yads_field in yads_type.fields:
            with self.conversion_context(field=yads_field.name):
                field_result = self._convert_field(yads_field)
                fields.append(field_result)
        return pa.struct(fields)

    @_convert_type.register(ytypes.Map)
    def _(self, yads_type: ytypes.Map) -> pa.DataType:
        import pyarrow as pa  # type: ignore[import-untyped]

        key_type = self._convert_type(yads_type.key)
        item_type = self._convert_type(yads_type.value)
        return pa.map_(key_type, item_type, keys_sorted=yads_type.keys_sorted)

    @_convert_type.register(ytypes.JSON)
    def _(self, yads_type: ytypes.JSON) -> pa.DataType:
        import pyarrow as pa  # type: ignore[import-untyped]

        json_constructor = self._get_version_gated_constructor(
            constructor_name="json_",
            min_version="19.0.0",
            feature_description="JSON type",
        )
        if json_constructor is None:
            return self.config.fallback_type
        return json_constructor(storage_type=pa.utf8())

    @_convert_type.register(ytypes.UUID)
    def _(self, yads_type: ytypes.UUID) -> pa.DataType:
        uuid_constructor = self._get_version_gated_constructor(
            constructor_name="uuid",
            min_version="18.0.0",
            feature_description="UUID type",
        )
        if uuid_constructor is None:
            return self.config.fallback_type
        return uuid_constructor()

    @_convert_type.register(ytypes.Void)
    def _(self, yads_type: ytypes.Void) -> pa.DataType:
        import pyarrow as pa  # type: ignore[import-untyped]

        return pa.null()

    @_convert_type.register(ytypes.Tensor)
    def _(self, yads_type: ytypes.Tensor) -> pa.DataType:
        import pyarrow as pa  # type: ignore[import-untyped]

        element_type = self._convert_type(yads_type.element)
        return pa.fixed_shape_tensor(element_type, yads_type.shape)

    def _convert_field(self, field: yspec.Field) -> pa.Field:
        import pyarrow as pa  # type: ignore[import-untyped]

        pa_type = self._convert_type(field.type)
        metadata = self._build_field_metadata(field)
        return pa.field(
            field.name,
            pa_type,
            nullable=field.is_nullable,
            metadata=metadata,
        )

    def _convert_field_default(self, field: yspec.Field) -> pa.Field:
        return self._convert_field(field)

    # %% ---- Helpers -----------------------------------------------------------------
    @staticmethod
    def _to_pa_time_unit(unit: ytypes.TimeUnit | None) -> str:
        if unit is None:
            return "ms"
        return unit.value

    def _build_timestamp(
        self, unit: ytypes.TimeUnit | None, tz: str | None
    ) -> pa.DataType:
        import pyarrow as pa  # type: ignore[import-untyped]

        pa_unit = self._to_pa_time_unit(unit)
        return pa.timestamp(pa_unit, tz=tz)

    def _build_field_metadata(self, field: yspec.Field) -> dict[str, str] | None:
        metadata: dict[str, Any] = {}
        if field.description is not None:
            metadata["description"] = field.description
        if field.metadata:
            metadata.update(field.metadata)
        return self._coerce_metadata(metadata) if metadata else None

    @staticmethod
    def _coerce_metadata(metadata: dict[str, Any]) -> dict[str, str]:
        """Coerce arbitrary metadata values to strings for PyArrow.

        PyArrow's KeyValueMetadata requires both keys and values to be
        strings (or bytes). This helper converts keys via `str(key)` and
        values as follows:

        - If the value is already a string, use it as-is
        - Otherwise, JSON-encode the value to preserve structure and types

        Args:
            metadata: Arbitrary key-value metadata mapping.

        Returns:
            A mapping of `str` to `str` suitable for pyarrow.
        """
        coerced: dict[str, str] = {}
        for k, v in metadata.items():
            sk = str(k)
            if isinstance(v, str):
                coerced[sk] = v
            else:
                coerced[sk] = json.dumps(v, separators=(",", ":"))
        return coerced

    def _get_version_gated_constructor(
        self,
        *,
        constructor_name: str,
        min_version: str,
        feature_description: str,
    ) -> Any | None:
        """Attempt to import a version-gated PyArrow type constructor with mode-aware fallback."""
        context = f"{feature_description} for '{self._field_context}'"

        imported_constructor, error_msg = try_import_optional(
            "pyarrow",
            required_import=constructor_name,
            package_name="pyarrow",
            min_version=min_version,
            context=context,
        )

        if imported_constructor is not None:
            return imported_constructor

        # Constructor is unavailable - handle based on mode
        self.raise_or_coerce(error_msg=error_msg)
        return None

__init__(config=None)

Initialize the PyArrowConverter.

Parameters:

Name Type Description Default
config PyArrowConverterConfig | None

Configuration object. If None, uses default PyArrowConverterConfig.

None
Source code in src/yads/converters/pyarrow_converter.py
128
129
130
131
132
133
134
135
def __init__(self, config: PyArrowConverterConfig | None = None) -> None:
    """Initialize the PyArrowConverter.

    Args:
        config: Configuration object. If None, uses default PyArrowConverterConfig.
    """
    self.config: PyArrowConverterConfig = config or PyArrowConverterConfig()
    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 pyarrow.Schema.

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 schema and emit warnings.

None

Returns:

Type Description
Any

A pyarrow.Schema with fields mapped from the spec columns.

Source code in src/yads/converters/pyarrow_converter.py
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
@requires_dependency("pyarrow", import_name="pyarrow")
def convert(
    self,
    spec: yspec.YadsSpec,
    *,
    mode: Literal["raise", "coerce"] | None = None,
) -> Any:
    """Convert a yads `YadsSpec` into a `pyarrow.Schema`.

    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 schema and emit warnings.

    Returns:
        A `pyarrow.Schema` with fields mapped from the spec columns.
    """
    import pyarrow as pa  # type: ignore[import-untyped]

    fields: list[pa.Field] = []
    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_result = self._convert_field_with_overrides(col)
                fields.append(field_result)
    schema_metadata = self._coerce_metadata(spec.metadata) if spec.metadata else None
    return pa.schema(fields, metadata=schema_metadata)

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)

PyArrowConverterConfig offers fine grained control over string/list sizing, column overrides, and fallback coercions for unsupported logical types.

PyArrowConverterConfig dataclass

Bases: BaseConverterConfig[Any]

Configuration for PyArrowConverter.

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, PyArrowConverter], Field]]

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

(lambda: MappingProxyType({}))()
use_large_string bool

If True, use pa.large_string() for String. Defaults to False.

False
use_large_binary bool

If True, use pa.large_binary() for Binary(length=None). When a fixed length is provided, a fixed-size pa.binary(length) is always used. Defaults to False.

False
use_large_list bool

If True, use pa.large_list(element) for variable-length Array (i.e., size is None). For fixed-size arrays (size set), pa.list_(element, list_size=size) is used. Defaults to False.

False
fallback_type DataType | None

PyArrow data type to use for unsupported types in coerce mode. Must be one of: pa.binary(), pa.large_binary(), pa.string(), pa.large_string(), or None. Defaults to None.

None
Source code in src/yads/converters/pyarrow_converter.py
 51
 52
 53
 54
 55
 56
 57
 58
 59
 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
101
102
103
104
@dataclass(frozen=True)
class PyArrowConverterConfig(BaseConverterConfig[Any]):
    """Configuration for PyArrowConverter.

    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 PyArrow field conversion. Inherited from BaseConverterConfig.
            Defaults to empty mapping.
        use_large_string: If True, use `pa.large_string()` for
            `String`. Defaults to False.
        use_large_binary: If True, use `pa.large_binary()` for
            `Binary(length=None)`. When a fixed `length` is provided, a fixed-size
            `pa.binary(length)` is always used. Defaults to False.
        use_large_list: If True, use `pa.large_list(element)` for
            variable-length `Array` (i.e., `size is None`). For fixed-size arrays
            (`size` set), `pa.list_(element, list_size=size)` is used. Defaults to False.
        fallback_type: PyArrow data type to use for unsupported types in coerce mode.
            Must be one of: pa.binary(), pa.large_binary(), pa.string(), pa.large_string(), or None.
            Defaults to None.
    """

    use_large_string: bool = False
    use_large_binary: bool = False
    use_large_list: bool = False
    fallback_type: pa.DataType | None = None
    column_overrides: Mapping[
        str, Callable[[yspec.Field, PyArrowConverter], pa.Field]
    ] = 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:
            import pyarrow as pa  # type: ignore[import-untyped]

            valid_fallback_types = {
                pa.binary(),
                pa.large_binary(),
                pa.string(),
                pa.large_string(),
            }
            if self.fallback_type not in valid_fallback_types:
                raise UnsupportedFeatureError(
                    f"fallback_type must be one of: pa.binary(), pa.large_binary(), "
                    f"pa.string(), pa.large_string(), or None. Got: {self.fallback_type}"
                )

__post_init__()

Validate configuration parameters.

Source code in src/yads/converters/pyarrow_converter.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def __post_init__(self) -> None:
    """Validate configuration parameters."""
    super().__post_init__()

    # Validate fallback_type if provided
    if self.fallback_type is not None:
        import pyarrow as pa  # type: ignore[import-untyped]

        valid_fallback_types = {
            pa.binary(),
            pa.large_binary(),
            pa.string(),
            pa.large_string(),
        }
        if self.fallback_type not in valid_fallback_types:
            raise UnsupportedFeatureError(
                f"fallback_type must be one of: pa.binary(), pa.large_binary(), "
                f"pa.string(), pa.large_string(), or None. Got: {self.fallback_type}"
            )