Skip to content

PySpark Converter

PySparkConverter produces pyspark.sql.types.StructType schemas from a YadsSpec. Use it to keep DataFrame builders synchronized with the canonical spec while still allowing overrides, column filters, and fallback types for unsupported constructs.

import yads
from yads.converters import PySparkConverter, PySparkConverterConfig
import json

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

converter = PySparkConverter(PySparkConverterConfig(mode="coerce"))
schema = converter.convert(spec)
print(json.dumps(schema.jsonValue(), indent=2))
{
  "type": "struct",
  "fields": [
    {
      "name": "submission_id",
      "type": "long",
      "nullable": false,
      "metadata": {}
    },
    {
      "name": "completion_percent",
      "type": "decimal(5,2)",
      "nullable": true,
      "metadata": {}
    },
    {
      "name": "time_taken_seconds",
      "type": "integer",
      "nullable": true,
      "metadata": {}
    },
    {
      "name": "submitted_at",
      "type": "timestamp",
      "nullable": true,
      "metadata": {}
    }
  ]
}

Info

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

PySparkConverter

Bases: BaseConverter[Any]

Convert a yads YadsSpec into a PySpark StructType.

The converter maps each yads column to a StructField and assembles a StructType. 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 unsigned integers to signed ones, or map unsupported types to StringType).

Notes
  • Time types are not supported by PySpark and raise UnsupportedFeatureError unless in coerce mode.
  • Duration types are not supported by PySpark and raise UnsupportedFeatureError unless in coerce mode.
  • Geometry, Geography, JSON, UUID, and Tensor types are not supported and raise UnsupportedFeatureError unless in coerce mode.
  • Variant type maps to VariantType if available in the PySpark version.
Source code in src/yads/converters/pyspark_converter.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
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
class PySparkConverter(BaseConverter[Any]):
    """Convert a yads `YadsSpec` into a PySpark `StructType`.

    The converter maps each yads column to a `StructField` and assembles a
    `StructType`. 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 unsigned integers to signed ones, or map unsupported types
    to StringType).

    Notes:
        - Time types are not supported by PySpark and raise `UnsupportedFeatureError`
          unless in coerce mode.
        - Duration types are not supported by PySpark and raise `UnsupportedFeatureError`
          unless in coerce mode.
        - Geometry, Geography, JSON, UUID, and Tensor types are not supported and raise
          `UnsupportedFeatureError` unless in coerce mode.
        - Variant type maps to VariantType if available in the PySpark version.
    """

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

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

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

        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 PySpark `StructType` with fields mapped from the spec columns.
        """
        from pyspark.sql.types import StructType

        fields: list[StructField] = []
        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)
        return StructType(fields)

    # %% ---- Type conversion ---------------------------------------------------------
    @singledispatchmethod
    def _convert_type(self, yads_type: ytypes.YadsType) -> DataType:
        # Fallback for currently unsupported types
        # - Time
        # - Duration
        # - JSON
        # - Geometry
        # - Geography
        # - UUID
        # - Tensor
        return self.raise_or_coerce(yads_type)

    @_convert_type.register(ytypes.String)
    def _(self, yads_type: ytypes.String) -> DataType:
        from pyspark.sql.types import StringType

        if yads_type.length is not None:
            # VarcharType/CharType types are not supported in PySpark DataFrame schemas
            return self.raise_or_coerce(
                coerce_type=StringType(),
                error_msg=(
                    f"String with fixed length is not supported in PySpark "
                    f"DataFrame schemas for '{self._field_context}'."
                ),
            )

        return StringType()

    @_convert_type.register(ytypes.Integer)
    def _(self, yads_type: ytypes.Integer) -> DataType:
        from pyspark.sql.types import (
            ByteType,
            ShortType,
            IntegerType,
            LongType,
            DecimalType,
        )

        bits = yads_type.bits or 32
        signed = yads_type.signed

        if signed:
            mapping = {
                8: ByteType(),
                16: ShortType(),
                32: IntegerType(),
                64: LongType(),
            }
            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
        else:
            # Handle unsigned integers
            if bits == 8:
                return self.raise_or_coerce(
                    coerce_type=ShortType(),
                    error_msg=(
                        f"Unsigned Integer(bits=8) is not supported by PySpark"
                        f" for '{self._field_context}'."
                    ),
                )
            elif bits == 16:
                return self.raise_or_coerce(
                    coerce_type=IntegerType(),
                    error_msg=(
                        f"Unsigned Integer(bits=16) is not supported by PySpark"
                        f" for '{self._field_context}'."
                    ),
                )
            elif bits == 32:
                return self.raise_or_coerce(
                    coerce_type=LongType(),
                    error_msg=(
                        f"Unsigned Integer(bits=32) is not supported by PySpark"
                        f" for '{self._field_context}'."
                    ),
                )
            elif bits == 64:
                return self.raise_or_coerce(
                    coerce_type=DecimalType(20, 0),
                    error_msg=(
                        f"Unsigned Integer(bits=64) is not supported by PySpark"
                        f" for '{self._field_context}'."
                    ),
                )
            else:
                raise UnsupportedFeatureError(
                    f"Unsupported Integer bits: {bits}. Expected 8/16/32/64"
                    f" for '{self._field_context}'."
                )

    @_convert_type.register(ytypes.Float)
    def _(self, yads_type: ytypes.Float) -> DataType:
        from pyspark.sql.types import (
            FloatType,
            DoubleType,
        )

        bits = yads_type.bits or 32

        if bits == 16:
            return self.raise_or_coerce(yads_type, coerce_type=FloatType())
        elif bits == 32:
            return FloatType()
        elif bits == 64:
            return DoubleType()
        else:
            raise UnsupportedFeatureError(
                f"Unsupported Float bits: {bits}. Expected 16/32/64"
                f" for '{self._field_context}'."
            )

    @_convert_type.register(ytypes.Decimal)
    def _(self, yads_type: ytypes.Decimal) -> DataType:
        from pyspark.sql.types import DecimalType

        precision = yads_type.precision or 38
        scale = yads_type.scale or 18
        return DecimalType(precision, scale)

    @_convert_type.register(ytypes.Boolean)
    def _(self, yads_type: ytypes.Boolean) -> DataType:
        from pyspark.sql.types import BooleanType

        return BooleanType()

    @_convert_type.register(ytypes.Binary)
    def _(self, yads_type: ytypes.Binary) -> DataType:
        from pyspark.sql.types import BinaryType

        # Ignore length parameter
        if yads_type.length is not None:
            self.raise_or_coerce(
                coerce_type=BinaryType(),
                error_msg=(
                    f"{yads_type} cannot be represented in PySpark; "
                    f"length constraint will be lost for '{self._field_context}'."
                ),
            )
        return BinaryType()

    @_convert_type.register(ytypes.Date)
    def _(self, yads_type: ytypes.Date) -> DataType:
        from pyspark.sql.types import DateType

        # Ignore bit-width parameter
        if yads_type.bits is not None:
            self.raise_or_coerce(
                coerce_type=DateType(),
                error_msg=(
                    f"{yads_type} cannot be represented in PySpark; "
                    f"bits constraint will be lost for '{self._field_context}'."
                ),
            )
        return DateType()

    @_convert_type.register(ytypes.Timestamp)
    def _(self, yads_type: ytypes.Timestamp) -> DataType:
        from pyspark.sql.types import TimestampType

        # Ignore unit parameter
        if yads_type.unit is not None:
            self.raise_or_coerce(
                coerce_type=TimestampType(),
                error_msg=(
                    f"{yads_type} cannot be represented in PySpark; "
                    f"unit constraint will be lost for '{self._field_context}'."
                ),
            )
        return TimestampType()

    @_convert_type.register(ytypes.TimestampTZ)
    def _(self, yads_type: ytypes.TimestampTZ) -> DataType:
        from pyspark.sql.types import TimestampType

        # Ignore unit parameter and tz parameter
        if yads_type.unit is not None:
            self.raise_or_coerce(
                coerce_type=TimestampType(),
                error_msg=(
                    f"{yads_type} cannot be represented in PySpark; "
                    f"unit and/or tz constraints will be lost for '{self._field_context}'."
                ),
            )
        return TimestampType()

    @_convert_type.register(ytypes.TimestampLTZ)
    def _(self, yads_type: ytypes.TimestampLTZ) -> DataType:
        from pyspark.sql.types import TimestampType

        # Ignore unit parameter
        if yads_type.unit is not None:
            self.raise_or_coerce(
                coerce_type=TimestampType(),
                error_msg=(
                    f"{yads_type} cannot be represented in PySpark; "
                    f"unit constraint will be lost for '{self._field_context}'."
                ),
            )
        return TimestampType()

    @_convert_type.register(ytypes.TimestampNTZ)
    def _(self, yads_type: ytypes.TimestampNTZ) -> DataType:
        TimestampNTZType, error_msg = self._get_version_gated_type(
            type_name="TimestampNTZType",
            min_version="3.4.0",
            feature_description="TimestampNTZ type",
        )
        if TimestampNTZType is None:
            return self.raise_or_coerce(yads_type, error_msg=error_msg)
        # Ignore unit parameter
        if yads_type.unit is not None:
            self.raise_or_coerce(
                coerce_type=TimestampNTZType(),
                error_msg=(
                    f"{yads_type} cannot be represented in PySpark; "
                    f"unit constraint will be lost for '{self._field_context}'."
                ),
            )
        return TimestampNTZType()

    @_convert_type.register(ytypes.Interval)
    def _(self, yads_type: ytypes.Interval) -> DataType:
        start_field = yads_type.interval_start
        end_field = yads_type.interval_end or start_field

        # Map interval units to PySpark constants
        year_month_units = {
            ytypes.IntervalTimeUnit.YEAR,
            ytypes.IntervalTimeUnit.MONTH,
        }
        day_time_units = {
            ytypes.IntervalTimeUnit.DAY,
            ytypes.IntervalTimeUnit.HOUR,
            ytypes.IntervalTimeUnit.MINUTE,
            ytypes.IntervalTimeUnit.SECOND,
        }

        # PySpark interval field constants
        YEAR = 0
        MONTH = 1
        DAY = 0
        HOUR = 1
        MINUTE = 2
        SECOND = 3

        if start_field in year_month_units:
            # Validate end_field is compatible
            if end_field not in year_month_units:
                raise UnsupportedFeatureError(
                    f"Invalid interval combination: {start_field} to {end_field}. "
                    f"Year-Month intervals must use YEAR or MONTH units only"
                    f" for '{self._field_context}'."
                )

            YearMonthIntervalType, error_msg = self._get_version_gated_type(
                type_name="YearMonthIntervalType",
                min_version="3.5.0",
                feature_description="Interval type with year-month units",
            )
            if YearMonthIntervalType is None:
                return self.raise_or_coerce(yads_type, error_msg=error_msg)

            start_val = YEAR if start_field == ytypes.IntervalTimeUnit.YEAR else MONTH
            end_val = YEAR if end_field == ytypes.IntervalTimeUnit.YEAR else MONTH
            return YearMonthIntervalType(start_val, end_val)
        elif start_field in day_time_units:
            # Validate end_field is compatible
            if end_field not in day_time_units:
                raise UnsupportedFeatureError(
                    f"Invalid interval combination: {start_field} to {end_field}. "
                    f"Day-Time intervals must use DAY, HOUR, MINUTE, or SECOND units only"
                    f" for '{self._field_context}'."
                )

            DayTimeIntervalType, error_msg = self._get_version_gated_type(
                type_name="DayTimeIntervalType",
                min_version="3.2.0",
                feature_description="Interval type with day-time units",
            )
            if DayTimeIntervalType is None:
                return self.raise_or_coerce(yads_type, error_msg=error_msg)

            start_val = {
                ytypes.IntervalTimeUnit.DAY: DAY,
                ytypes.IntervalTimeUnit.HOUR: HOUR,
                ytypes.IntervalTimeUnit.MINUTE: MINUTE,
                ytypes.IntervalTimeUnit.SECOND: SECOND,
            }[start_field]
            end_val = {
                ytypes.IntervalTimeUnit.DAY: DAY,
                ytypes.IntervalTimeUnit.HOUR: HOUR,
                ytypes.IntervalTimeUnit.MINUTE: MINUTE,
                ytypes.IntervalTimeUnit.SECOND: SECOND,
            }[end_field]
            return DayTimeIntervalType(startField=start_val, endField=end_val)
        else:
            raise UnsupportedFeatureError(
                f"Unsupported interval start field: {start_field}"
                f" for '{self._field_context}'."
            )

    @_convert_type.register(ytypes.Array)
    def _(self, yads_type: ytypes.Array) -> DataType:
        from pyspark.sql.types import ArrayType

        # Ignore size parameter
        element_type = self._convert_type(yads_type.element)
        if yads_type.size is not None:
            self.raise_or_coerce(
                coerce_type=ArrayType(element_type, True),
                error_msg=(
                    f"{yads_type} cannot be represented in PySpark; "
                    f"size constraint will be lost for '{self._field_context}'."
                ),
            )
        return ArrayType(element_type, True)

    @_convert_type.register(ytypes.Struct)
    def _(self, yads_type: ytypes.Struct) -> DataType:
        from pyspark.sql.types import StructType

        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 StructType(fields)

    @_convert_type.register(ytypes.Map)
    def _(self, yads_type: ytypes.Map) -> DataType:
        from pyspark.sql.types import MapType

        key_type = self._convert_type(yads_type.key)
        value_type = self._convert_type(yads_type.value)
        return MapType(keyType=key_type, valueType=value_type, valueContainsNull=True)

    @_convert_type.register(ytypes.Void)
    def _(self, yads_type: ytypes.Void) -> DataType:
        from pyspark.sql.types import NullType

        return NullType()

    @_convert_type.register(ytypes.Variant)
    def _(self, yads_type: ytypes.Variant) -> DataType:
        VariantType, error_msg = self._get_version_gated_type(
            type_name="VariantType",
            min_version="4.0.0",
            feature_description="Variant type",
        )
        if VariantType is None:
            return self.raise_or_coerce(yads_type, error_msg=error_msg)
        return VariantType()

    def _convert_field(self, field: yspec.Field) -> StructField:
        from pyspark.sql.types import StructField

        spark_type = self._convert_type(field.type)
        metadata: dict[str, Any] = {}
        if field.description is not None:
            metadata["description"] = field.description
        if field.metadata:
            metadata.update(field.metadata)

        return StructField(
            field.name,
            spark_type,
            nullable=field.is_nullable,
            metadata=metadata or None,
        )

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

    # %% ---- Helpers -----------------------------------------------------------------
    def _get_version_gated_type(
        self,
        *,
        type_name: str,
        min_version: str,
        feature_description: str,
    ) -> tuple[type | None, str | None]:
        """Attempt to import a version-gated PySpark type."""
        context = f"{feature_description} for '{self._field_context}'"

        imported_type, error_msg = try_import_optional(
            "pyspark.sql.types",
            required_import=type_name,
            package_name="pyspark",
            min_version=min_version,
            context=context,
        )

        return imported_type, error_msg

__init__(config=None)

Initialize the PySparkConverter.

Parameters:

Name Type Description Default
config PySparkConverterConfig | None

Configuration object. If None, uses default PySparkConverterConfig.

None
Source code in src/yads/converters/pyspark_converter.py
108
109
110
111
112
113
114
115
def __init__(self, config: PySparkConverterConfig | None = None) -> None:
    """Initialize the PySparkConverter.

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

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
StructType

A PySpark StructType with fields mapped from the spec columns.

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

    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 PySpark `StructType` with fields mapped from the spec columns.
    """
    from pyspark.sql.types import StructType

    fields: list[StructField] = []
    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)
    return StructType(fields)

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)

PySparkConverterConfig dataclass

Bases: BaseConverterConfig[Any]

Configuration for PySparkConverter.

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, PySparkConverter], StructField]]

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

(lambda: MappingProxyType({}))()
fallback_type DataType | None

PySpark data type to use for unsupported types in coerce mode. Must be one of: StringType(), BinaryType(), or None. Defaults to None.

None
Source code in src/yads/converters/pyspark_converter.py
45
46
47
48
49
50
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
@dataclass(frozen=True)
class PySparkConverterConfig(BaseConverterConfig[Any]):
    """Configuration for PySparkConverter.

    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 PySpark field conversion. Inherited from BaseConverterConfig.
            Defaults to empty mapping.
        fallback_type: PySpark data type to use for unsupported types in coerce mode.
            Must be one of: StringType(), BinaryType(), or None. Defaults to None.
    """

    fallback_type: DataType | None = None
    column_overrides: Mapping[str, Callable[[Field, PySparkConverter], StructField]] = (
        field(default_factory=lambda: MappingProxyType({}))
    )

    def __post_init__(self) -> None:
        super().__post_init__()
        # Validate fallback_type if provided
        if self.fallback_type is not None:
            from pyspark.sql.types import (
                StringType,
                BinaryType,
            )

            valid_fallback_types = (StringType, BinaryType)
            if not isinstance(self.fallback_type, valid_fallback_types):
                raise UnsupportedFeatureError(
                    "fallback_type must be one of: StringType(), BinaryType(), or None. "
                    f"Got: {self.fallback_type}"
                )