Skip to content

converter

xsdata.formats.converter

Converter

Bases: ABC

Abstract converter class.

Source code in xsdata/formats/converter.py
36
37
38
39
40
41
42
43
44
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
class Converter(abc.ABC):
    """Abstract converter class."""

    @abc.abstractmethod
    def deserialize(self, value: Any, **kwargs: Any) -> Any:
        """Convert a value to a python type.

        Args:
            value: The input value
            **kwargs: Additional keyword arguments needed per converter

        Returns:
            The converted value.

        Raises:
            ConverterError: if the value can't be converted.
        """

    @abc.abstractmethod
    def serialize(self, value: Any, **kwargs: Any) -> str:
        """Convert value to string for serialization.

        Args:
            value: The input value
            **kwargs: Additional keyword arguments needed per converter

        Returns:
            The converted string value.
        """

    @classmethod
    def validate_input_type(cls, value: Any, tp: Type):
        """Validate the input value type matches the required type."""
        if not isinstance(value, tp):
            raise ConverterError(
                f"Input value must be '{tp.__name__}' got '{type(value).__name__}'"
            )

deserialize(value, **kwargs) abstractmethod

Convert a value to a python type.

Parameters:

Name Type Description Default
value Any

The input value

required
**kwargs Any

Additional keyword arguments needed per converter

{}

Returns:

Type Description
Any

The converted value.

Raises:

Type Description
ConverterError

if the value can't be converted.

Source code in xsdata/formats/converter.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@abc.abstractmethod
def deserialize(self, value: Any, **kwargs: Any) -> Any:
    """Convert a value to a python type.

    Args:
        value: The input value
        **kwargs: Additional keyword arguments needed per converter

    Returns:
        The converted value.

    Raises:
        ConverterError: if the value can't be converted.
    """

serialize(value, **kwargs) abstractmethod

Convert value to string for serialization.

Parameters:

Name Type Description Default
value Any

The input value

required
**kwargs Any

Additional keyword arguments needed per converter

{}

Returns:

Type Description
str

The converted string value.

Source code in xsdata/formats/converter.py
54
55
56
57
58
59
60
61
62
63
64
@abc.abstractmethod
def serialize(self, value: Any, **kwargs: Any) -> str:
    """Convert value to string for serialization.

    Args:
        value: The input value
        **kwargs: Additional keyword arguments needed per converter

    Returns:
        The converted string value.
    """

validate_input_type(value, tp) classmethod

Validate the input value type matches the required type.

Source code in xsdata/formats/converter.py
66
67
68
69
70
71
72
@classmethod
def validate_input_type(cls, value: Any, tp: Type):
    """Validate the input value type matches the required type."""
    if not isinstance(value, tp):
        raise ConverterError(
            f"Input value must be '{tp.__name__}' got '{type(value).__name__}'"
        )

ConverterFactory

Converter factory class.

Attributes:

Name Type Description
registry Dict[Type, Converter]

The registered converters

Source code in xsdata/formats/converter.py
 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
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
class ConverterFactory:
    """Converter factory class.

    Attributes:
        registry: The registered converters
    """

    __slots__ = "registry"

    def __init__(self):
        self.registry: Dict[Type, Converter] = {}

    def deserialize(self, value: Any, types: Sequence[Type], **kwargs: Any) -> Any:
        """Attempt to convert any value to one of the given types.

        If all attempts fail return the value input value and emit a
        warning.

        Args:
            value: The input value
            types: The target candidate types
            **kwargs: Additional keyword arguments needed per converter

        Returns:
            The converted value or the input value.
        """
        for data_type in types:
            try:
                instance = self.type_converter(data_type)
                return instance.deserialize(value, data_type=data_type, **kwargs)
            except ConverterError:
                pass

        warnings.warn(
            f"Failed to convert value `{value}` to one of {types}", ConverterWarning
        )
        return value

    def serialize(self, value: Any, **kwargs: Any) -> Any:
        """Convert the given value to string.

        If the value is a list assume the value is a list of tokens.

        Args:
            value: The input value
            **kwargs: Additional keyword arguments needed per converter

        Returns:
            The converted string value or None if the input value is None.

        """
        if value is None:
            return None

        if isinstance(value, list):
            return " ".join(self.serialize(val, **kwargs) for val in value)

        instance = self.value_converter(value)
        return instance.serialize(value, **kwargs)

    def test(
        self,
        value: Optional[str],
        types: Sequence[Type],
        strict: bool = False,
        **kwargs: Any,
    ) -> bool:
        """Test the given string value can be converted to one of the given types.

        Args:
            value: The input value
            types: The candidate target types
            strict: validate the string output also matches the original input
            **kwargs: Additional keyword arguments needed per converter

        Returns:
            The bool result.
        """
        if not isinstance(value, str):
            return False

        with warnings.catch_warnings(record=True) as w:
            decoded = self.deserialize(value, types, **kwargs)

        if w and w[-1].category is ConverterWarning:
            return False

        if strict and isinstance(decoded, (float, int, Decimal, XmlPeriod)):
            if isinstance(decoded, float) and (
                math.isinf(decoded) or math.isnan(decoded)
            ):
                return True

            encoded = self.serialize(decoded, **kwargs)
            return value.strip() == encoded

        return True

    def register_converter(self, data_type: Type, func: Union[Callable, Converter]):
        """Register a callable or converter for the given data type.

        Args:
            data_type: The data type
            func: The callable or converter instance
        """
        if isinstance(func, Converter):
            self.registry[data_type] = func
        else:
            self.registry[data_type] = ProxyConverter(func)

    def unregister_converter(self, data_type: Type):
        """Unregister the converter for the given data type.

        Args:
            data_type: The data type

        Raises:
            KeyError: if the data type is not registered.
        """
        self.registry.pop(data_type)

    def type_converter(self, data_type: Type) -> Converter:
        """Find a suitable converter for given data type.

        Iterate over all but last mro items and check for registered
        converters, fall back to str and issue a warning if there are
        no matches.

        Args:
            data_type: The data type

        Returns:
            A converter instance
        """
        try:
            # Quick in and out, without checking the whole mro.
            return self.registry[data_type]
        except KeyError:
            pass

        # We tested the first, ignore the object
        for mro in data_type.__mro__[1:-1]:
            if mro in self.registry:
                return self.registry[mro]

        warnings.warn(f"No converter registered for `{data_type}`", ConverterWarning)
        return self.registry[str]

    def value_converter(self, value: Any) -> Converter:
        """Get a suitable converter for the given value."""
        return self.type_converter(value.__class__)

    @classmethod
    def sort_types(cls, types: Sequence[Type]) -> List[Type]:
        """Sort a list of types by giving priority to strict types first."""
        if len(types) < 2:
            return list(types)

        return sorted(types, key=lambda x: __PYTHON_TYPES_SORTED__.get(x, 0))

    @classmethod
    def explicit_types(cls) -> Tuple[Type, ...]:
        """Get a list of types that need strict test."""
        return __EXPLICIT_TYPES__

deserialize(value, types, **kwargs)

Attempt to convert any value to one of the given types.

If all attempts fail return the value input value and emit a warning.

Parameters:

Name Type Description Default
value Any

The input value

required
types Sequence[Type]

The target candidate types

required
**kwargs Any

Additional keyword arguments needed per converter

{}

Returns:

Type Description
Any

The converted value or the input value.

Source code in xsdata/formats/converter.py
 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
def deserialize(self, value: Any, types: Sequence[Type], **kwargs: Any) -> Any:
    """Attempt to convert any value to one of the given types.

    If all attempts fail return the value input value and emit a
    warning.

    Args:
        value: The input value
        types: The target candidate types
        **kwargs: Additional keyword arguments needed per converter

    Returns:
        The converted value or the input value.
    """
    for data_type in types:
        try:
            instance = self.type_converter(data_type)
            return instance.deserialize(value, data_type=data_type, **kwargs)
        except ConverterError:
            pass

    warnings.warn(
        f"Failed to convert value `{value}` to one of {types}", ConverterWarning
    )
    return value

serialize(value, **kwargs)

Convert the given value to string.

If the value is a list assume the value is a list of tokens.

Parameters:

Name Type Description Default
value Any

The input value

required
**kwargs Any

Additional keyword arguments needed per converter

{}

Returns:

Type Description
Any

The converted string value or None if the input value is None.

Source code in xsdata/formats/converter.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def serialize(self, value: Any, **kwargs: Any) -> Any:
    """Convert the given value to string.

    If the value is a list assume the value is a list of tokens.

    Args:
        value: The input value
        **kwargs: Additional keyword arguments needed per converter

    Returns:
        The converted string value or None if the input value is None.

    """
    if value is None:
        return None

    if isinstance(value, list):
        return " ".join(self.serialize(val, **kwargs) for val in value)

    instance = self.value_converter(value)
    return instance.serialize(value, **kwargs)

test(value, types, strict=False, **kwargs)

Test the given string value can be converted to one of the given types.

Parameters:

Name Type Description Default
value Optional[str]

The input value

required
types Sequence[Type]

The candidate target types

required
strict bool

validate the string output also matches the original input

False
**kwargs Any

Additional keyword arguments needed per converter

{}

Returns:

Type Description
bool

The bool result.

Source code in xsdata/formats/converter.py
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
def test(
    self,
    value: Optional[str],
    types: Sequence[Type],
    strict: bool = False,
    **kwargs: Any,
) -> bool:
    """Test the given string value can be converted to one of the given types.

    Args:
        value: The input value
        types: The candidate target types
        strict: validate the string output also matches the original input
        **kwargs: Additional keyword arguments needed per converter

    Returns:
        The bool result.
    """
    if not isinstance(value, str):
        return False

    with warnings.catch_warnings(record=True) as w:
        decoded = self.deserialize(value, types, **kwargs)

    if w and w[-1].category is ConverterWarning:
        return False

    if strict and isinstance(decoded, (float, int, Decimal, XmlPeriod)):
        if isinstance(decoded, float) and (
            math.isinf(decoded) or math.isnan(decoded)
        ):
            return True

        encoded = self.serialize(decoded, **kwargs)
        return value.strip() == encoded

    return True

register_converter(data_type, func)

Register a callable or converter for the given data type.

Parameters:

Name Type Description Default
data_type Type

The data type

required
func Union[Callable, Converter]

The callable or converter instance

required
Source code in xsdata/formats/converter.py
173
174
175
176
177
178
179
180
181
182
183
def register_converter(self, data_type: Type, func: Union[Callable, Converter]):
    """Register a callable or converter for the given data type.

    Args:
        data_type: The data type
        func: The callable or converter instance
    """
    if isinstance(func, Converter):
        self.registry[data_type] = func
    else:
        self.registry[data_type] = ProxyConverter(func)

unregister_converter(data_type)

Unregister the converter for the given data type.

Parameters:

Name Type Description Default
data_type Type

The data type

required

Raises:

Type Description
KeyError

if the data type is not registered.

Source code in xsdata/formats/converter.py
185
186
187
188
189
190
191
192
193
194
def unregister_converter(self, data_type: Type):
    """Unregister the converter for the given data type.

    Args:
        data_type: The data type

    Raises:
        KeyError: if the data type is not registered.
    """
    self.registry.pop(data_type)

type_converter(data_type)

Find a suitable converter for given data type.

Iterate over all but last mro items and check for registered converters, fall back to str and issue a warning if there are no matches.

Parameters:

Name Type Description Default
data_type Type

The data type

required

Returns:

Type Description
Converter

A converter instance

Source code in xsdata/formats/converter.py
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
def type_converter(self, data_type: Type) -> Converter:
    """Find a suitable converter for given data type.

    Iterate over all but last mro items and check for registered
    converters, fall back to str and issue a warning if there are
    no matches.

    Args:
        data_type: The data type

    Returns:
        A converter instance
    """
    try:
        # Quick in and out, without checking the whole mro.
        return self.registry[data_type]
    except KeyError:
        pass

    # We tested the first, ignore the object
    for mro in data_type.__mro__[1:-1]:
        if mro in self.registry:
            return self.registry[mro]

    warnings.warn(f"No converter registered for `{data_type}`", ConverterWarning)
    return self.registry[str]

value_converter(value)

Get a suitable converter for the given value.

Source code in xsdata/formats/converter.py
223
224
225
def value_converter(self, value: Any) -> Converter:
    """Get a suitable converter for the given value."""
    return self.type_converter(value.__class__)

sort_types(types) classmethod

Sort a list of types by giving priority to strict types first.

Source code in xsdata/formats/converter.py
227
228
229
230
231
232
233
@classmethod
def sort_types(cls, types: Sequence[Type]) -> List[Type]:
    """Sort a list of types by giving priority to strict types first."""
    if len(types) < 2:
        return list(types)

    return sorted(types, key=lambda x: __PYTHON_TYPES_SORTED__.get(x, 0))

explicit_types() classmethod

Get a list of types that need strict test.

Source code in xsdata/formats/converter.py
235
236
237
238
@classmethod
def explicit_types(cls) -> Tuple[Type, ...]:
    """Get a list of types that need strict test."""
    return __EXPLICIT_TYPES__

StringConverter

Bases: Converter

A str converter.

Source code in xsdata/formats/converter.py
271
272
273
274
275
276
277
278
279
280
class StringConverter(Converter):
    """A str converter."""

    def deserialize(self, value: Any, **kwargs: Any) -> Any:
        """Convert a value to string."""
        return value if isinstance(value, str) else str(value)

    def serialize(self, value: Any, **kwargs: Any) -> str:
        """Convert a value to string."""
        return value if isinstance(value, str) else str(value)

deserialize(value, **kwargs)

Convert a value to string.

Source code in xsdata/formats/converter.py
274
275
276
def deserialize(self, value: Any, **kwargs: Any) -> Any:
    """Convert a value to string."""
    return value if isinstance(value, str) else str(value)

serialize(value, **kwargs)

Convert a value to string.

Source code in xsdata/formats/converter.py
278
279
280
def serialize(self, value: Any, **kwargs: Any) -> str:
    """Convert a value to string."""
    return value if isinstance(value, str) else str(value)

BoolConverter

Bases: Converter

A bool converter.

Source code in xsdata/formats/converter.py
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
class BoolConverter(Converter):
    """A bool converter."""

    def deserialize(self, value: Any, **kwargs: Any) -> bool:
        """Convert a value to bool.

        Args:
            value: The input value
            **kwargs: Unused keyword arguments

        Returns:
            True if the value is in (True, "true", "1")
            False if the value is in (False, "false", "0")

        Raises:
            ConverterError: if the value can't be converted to bool.
        """
        if isinstance(value, str):
            val = value.strip()

            if val in ("true", "1"):
                return True

            if val in ("false", "0"):
                return False

            raise ConverterError(f"Invalid bool literal '{value}'")

        if value is True or value is False:
            return value

        raise ConverterError(f"Invalid bool literal '{value}'")

    def serialize(self, value: bool, **kwargs: Any) -> str:
        """Convert a bool value to string.

        Args:
            value: The input bool value
            **kwargs: Unused keyword arguments

        Returns:
            "true" or "false"
        """
        return "true" if value else "false"

deserialize(value, **kwargs)

Convert a value to bool.

Parameters:

Name Type Description Default
value Any

The input value

required
**kwargs Any

Unused keyword arguments

{}

Returns:

Type Description
bool

True if the value is in (True, "true", "1")

bool

False if the value is in (False, "false", "0")

Raises:

Type Description
ConverterError

if the value can't be converted to bool.

Source code in xsdata/formats/converter.py
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
def deserialize(self, value: Any, **kwargs: Any) -> bool:
    """Convert a value to bool.

    Args:
        value: The input value
        **kwargs: Unused keyword arguments

    Returns:
        True if the value is in (True, "true", "1")
        False if the value is in (False, "false", "0")

    Raises:
        ConverterError: if the value can't be converted to bool.
    """
    if isinstance(value, str):
        val = value.strip()

        if val in ("true", "1"):
            return True

        if val in ("false", "0"):
            return False

        raise ConverterError(f"Invalid bool literal '{value}'")

    if value is True or value is False:
        return value

    raise ConverterError(f"Invalid bool literal '{value}'")

serialize(value, **kwargs)

Convert a bool value to string.

Parameters:

Name Type Description Default
value bool

The input bool value

required
**kwargs Any

Unused keyword arguments

{}

Returns:

Type Description
str

"true" or "false"

Source code in xsdata/formats/converter.py
316
317
318
319
320
321
322
323
324
325
326
def serialize(self, value: bool, **kwargs: Any) -> str:
    """Convert a bool value to string.

    Args:
        value: The input bool value
        **kwargs: Unused keyword arguments

    Returns:
        "true" or "false"
    """
    return "true" if value else "false"

IntConverter

Bases: Converter

An int converter.

Source code in xsdata/formats/converter.py
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
class IntConverter(Converter):
    """An int converter."""

    def deserialize(self, value: Any, **kwargs: Any) -> int:
        """Convert a value to int.

        Args:
            value: The input value
            **kwargs: Unused keyword arguments

        Returns:
            The int converted value.

        Raises:
            ConverterError: on value or type errors.
        """
        try:
            return int(value)
        except (ValueError, TypeError) as e:
            raise ConverterError(e)

    def serialize(self, value: int, **kwargs: Any) -> str:
        """Convert an int value sto string.

        Args:
            value: The input int value
            **kwargs: Unused keyword arguments

        Returns:
            The str converted value.
        """
        return str(value)

deserialize(value, **kwargs)

Convert a value to int.

Parameters:

Name Type Description Default
value Any

The input value

required
**kwargs Any

Unused keyword arguments

{}

Returns:

Type Description
int

The int converted value.

Raises:

Type Description
ConverterError

on value or type errors.

Source code in xsdata/formats/converter.py
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
def deserialize(self, value: Any, **kwargs: Any) -> int:
    """Convert a value to int.

    Args:
        value: The input value
        **kwargs: Unused keyword arguments

    Returns:
        The int converted value.

    Raises:
        ConverterError: on value or type errors.
    """
    try:
        return int(value)
    except (ValueError, TypeError) as e:
        raise ConverterError(e)

serialize(value, **kwargs)

Convert an int value sto string.

Parameters:

Name Type Description Default
value int

The input int value

required
**kwargs Any

Unused keyword arguments

{}

Returns:

Type Description
str

The str converted value.

Source code in xsdata/formats/converter.py
350
351
352
353
354
355
356
357
358
359
360
def serialize(self, value: int, **kwargs: Any) -> str:
    """Convert an int value sto string.

    Args:
        value: The input int value
        **kwargs: Unused keyword arguments

    Returns:
        The str converted value.
    """
    return str(value)

FloatConverter

Bases: Converter

A float converter.

Source code in xsdata/formats/converter.py
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
class FloatConverter(Converter):
    """A float converter."""

    INF = float("inf")

    def deserialize(self, value: Any, **kwargs: Any) -> float:
        """Convert a value to float.

        Args:
            value: The input value
            **kwargs: Unused keyword arguments

        Returns:
            The float converted value.

        Raises:
            ConverterError: on value errors.
        """
        try:
            return float(value)
        except ValueError as e:
            raise ConverterError(e)

    def serialize(self, value: float, **kwargs: Any) -> str:
        """Convert a float value sto string.

        Args:
            value: The input int value
            **kwargs: Unused keyword arguments

        Returns:
            The str converted value.
        """
        if math.isnan(value):
            return "NaN"

        if value == self.INF:
            return "INF"

        if value == -self.INF:
            return "-INF"

        return repr(value).upper().replace("E+", "E")

deserialize(value, **kwargs)

Convert a value to float.

Parameters:

Name Type Description Default
value Any

The input value

required
**kwargs Any

Unused keyword arguments

{}

Returns:

Type Description
float

The float converted value.

Raises:

Type Description
ConverterError

on value errors.

Source code in xsdata/formats/converter.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
def deserialize(self, value: Any, **kwargs: Any) -> float:
    """Convert a value to float.

    Args:
        value: The input value
        **kwargs: Unused keyword arguments

    Returns:
        The float converted value.

    Raises:
        ConverterError: on value errors.
    """
    try:
        return float(value)
    except ValueError as e:
        raise ConverterError(e)

serialize(value, **kwargs)

Convert a float value sto string.

Parameters:

Name Type Description Default
value float

The input int value

required
**kwargs Any

Unused keyword arguments

{}

Returns:

Type Description
str

The str converted value.

Source code in xsdata/formats/converter.py
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
def serialize(self, value: float, **kwargs: Any) -> str:
    """Convert a float value sto string.

    Args:
        value: The input int value
        **kwargs: Unused keyword arguments

    Returns:
        The str converted value.
    """
    if math.isnan(value):
        return "NaN"

    if value == self.INF:
        return "INF"

    if value == -self.INF:
        return "-INF"

    return repr(value).upper().replace("E+", "E")

BytesConverter

Bases: Converter

A bytes converter for base16 and base64 formats.

Source code in xsdata/formats/converter.py
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
class BytesConverter(Converter):
    """A bytes converter for base16 and base64 formats."""

    def deserialize(self, value: Any, **kwargs: Any) -> bytes:
        """Convert a string value to base16 or base64 format.

        Args:
            value: The input string value
            **kwargs: Additional keyword arguments
                format: The target output format (base16|base64)

        Returns:
            The bytes converted value.

        Raises:
            ConverterError: If format is empty or not supported or the value
                contains invalid characters.
        """
        self.validate_input_type(value, str)

        try:
            fmt = kwargs.get("format")

            if fmt == "base16":
                return binascii.unhexlify(value)

            if fmt == "base64":
                return base64.b64decode(value, validate=True)

            raise ConverterError(f"Unknown format '{fmt}'")
        except ValueError as e:
            raise ConverterError(e)

    def serialize(self, value: bytes, **kwargs: Any) -> str:
        """Convert a bytes value sto string.

        Args:
            value: The input bytes value
            **kwargs: Additional keyword arguments
                format: The input value format (base16|base64)

        Returns:
            The str converted value.

        Raises:
            ConverterError: If format doesn't match the value type or
                it's not supported.
        """
        fmt = kwargs.get("format")

        if isinstance(value, XmlHexBinary) or fmt == "base16":
            return base64.b16encode(value).decode()

        if isinstance(value, XmlBase64Binary) or fmt == "base64":
            return base64.b64encode(value).decode()

        raise ConverterError(f"Unknown format '{fmt}'")

deserialize(value, **kwargs)

Convert a string value to base16 or base64 format.

Parameters:

Name Type Description Default
value Any

The input string value

required
**kwargs Any

Additional keyword arguments format: The target output format (base16|base64)

{}

Returns:

Type Description
bytes

The bytes converted value.

Raises:

Type Description
ConverterError

If format is empty or not supported or the value contains invalid characters.

Source code in xsdata/formats/converter.py
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
def deserialize(self, value: Any, **kwargs: Any) -> bytes:
    """Convert a string value to base16 or base64 format.

    Args:
        value: The input string value
        **kwargs: Additional keyword arguments
            format: The target output format (base16|base64)

    Returns:
        The bytes converted value.

    Raises:
        ConverterError: If format is empty or not supported or the value
            contains invalid characters.
    """
    self.validate_input_type(value, str)

    try:
        fmt = kwargs.get("format")

        if fmt == "base16":
            return binascii.unhexlify(value)

        if fmt == "base64":
            return base64.b64decode(value, validate=True)

        raise ConverterError(f"Unknown format '{fmt}'")
    except ValueError as e:
        raise ConverterError(e)

serialize(value, **kwargs)

Convert a bytes value sto string.

Parameters:

Name Type Description Default
value bytes

The input bytes value

required
**kwargs Any

Additional keyword arguments format: The input value format (base16|base64)

{}

Returns:

Type Description
str

The str converted value.

Raises:

Type Description
ConverterError

If format doesn't match the value type or it's not supported.

Source code in xsdata/formats/converter.py
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
def serialize(self, value: bytes, **kwargs: Any) -> str:
    """Convert a bytes value sto string.

    Args:
        value: The input bytes value
        **kwargs: Additional keyword arguments
            format: The input value format (base16|base64)

    Returns:
        The str converted value.

    Raises:
        ConverterError: If format doesn't match the value type or
            it's not supported.
    """
    fmt = kwargs.get("format")

    if isinstance(value, XmlHexBinary) or fmt == "base16":
        return base64.b16encode(value).decode()

    if isinstance(value, XmlBase64Binary) or fmt == "base64":
        return base64.b64encode(value).decode()

    raise ConverterError(f"Unknown format '{fmt}'")

DecimalConverter

Bases: Converter

A decimal converter.

Source code in xsdata/formats/converter.py
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
class DecimalConverter(Converter):
    """A decimal converter."""

    def deserialize(self, value: Any, **kwargs: Any) -> Decimal:
        """Convert a value to decimal.

        Args:
            value: The input value
            **kwargs: Unused keyword arguments

        Returns:
            The decimal converted value.

        Raises:
            ConverterError: on InvalidOperation errors.
        """
        try:
            return Decimal(value)
        except InvalidOperation:
            raise ConverterError

    def serialize(self, value: Decimal, **kwargs: Any) -> str:
        """Convert a decimal value sto string.

        Args:
            value: The input decimal value
            **kwargs: Unused keyword arguments

        Returns:
            The str converted value.
        """
        if value.is_infinite():
            return str(value).replace("Infinity", "INF")

        return f"{value:f}"

deserialize(value, **kwargs)

Convert a value to decimal.

Parameters:

Name Type Description Default
value Any

The input value

required
**kwargs Any

Unused keyword arguments

{}

Returns:

Type Description
Decimal

The decimal converted value.

Raises:

Type Description
ConverterError

on InvalidOperation errors.

Source code in xsdata/formats/converter.py
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
def deserialize(self, value: Any, **kwargs: Any) -> Decimal:
    """Convert a value to decimal.

    Args:
        value: The input value
        **kwargs: Unused keyword arguments

    Returns:
        The decimal converted value.

    Raises:
        ConverterError: on InvalidOperation errors.
    """
    try:
        return Decimal(value)
    except InvalidOperation:
        raise ConverterError

serialize(value, **kwargs)

Convert a decimal value sto string.

Parameters:

Name Type Description Default
value Decimal

The input decimal value

required
**kwargs Any

Unused keyword arguments

{}

Returns:

Type Description
str

The str converted value.

Source code in xsdata/formats/converter.py
488
489
490
491
492
493
494
495
496
497
498
499
500
501
def serialize(self, value: Decimal, **kwargs: Any) -> str:
    """Convert a decimal value sto string.

    Args:
        value: The input decimal value
        **kwargs: Unused keyword arguments

    Returns:
        The str converted value.
    """
    if value.is_infinite():
        return str(value).replace("Infinity", "INF")

    return f"{value:f}"

QNameConverter

Bases: Converter

A QName converter.

Source code in xsdata/formats/converter.py
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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
class QNameConverter(Converter):
    """A QName converter."""

    def deserialize(
        self,
        value: str,
        ns_map: Optional[Dict] = None,
        **kwargs: Any,
    ) -> QName:
        """Convert a string value to QName instance.

        The method supports strings with namespace prefixes
        or fully namespace qualified strings.

        Examples:
            - xs:string -> QName("http://www.w3.org/2001/XMLSchema", "string")
            - {foo}bar -> QName("foo", "bar"

        Args:
            value: The input str value
            ns_map: A namespace prefix-URI map
            **kwargs: Unused keyword arguments

        Returns:
            A QName instance

        Raises:
            ConverterError: If the prefix can't be resolved.
        """
        self.validate_input_type(value, str)
        namespace, tag = self.resolve(value, ns_map)

        return QName(namespace, tag) if namespace else QName(tag)

    def serialize(
        self,
        value: QName,
        ns_map: Optional[Dict] = None,
        **kwargs: Any,
    ) -> str:
        """Convert a QName instance value sto string.

        Convert a QName instance to string either with a namespace prefix if a
        prefix-URI namespaces mapping is provided or to a fully qualified name
        with the namespace.

        Examples:
            - QName("http://www.w3.org/2001/XMLSchema", "int") & ns_map -> xs:int
            - QName("foo, "bar") -> {foo}bar

        Args:
            value: The qname instance to convert
            ns_map: A namespace prefix-URI map, if we want to use prefixes
            **kwargs: Unused keyword arguments

        Returns:
            The str converted value.
        """
        if ns_map is None:
            return value.text

        namespace, tag = namespaces.split_qname(value.text)

        if not namespace:
            return tag

        prefix = namespaces.load_prefix(namespace, ns_map)

        return f"{prefix}:{tag}" if prefix else tag

    @staticmethod
    def resolve(value: str, ns_map: Optional[Dict] = None) -> Tuple[str, str]:
        """Split a qname or ns prefixed string value or a uri, name pair.

        Args:
            value: the input value to resolve
            ns_map: A namespace prefix-URI map

        Returns:
            A tuple of uri and name strings.

        Raises:
            ConverterError: if the uri is not valid,
                if the prefix can't be resolved to a URI,
                if the name is not a valid NCName
        """
        value = value.strip()

        if not value:
            raise ConverterError

        if value[0] == "{":
            uri, name = text.split(value[1:], "}")

            if not namespaces.is_uri(uri):
                raise ConverterError
        else:
            prefix, name = text.split(value, ":")
            uri = ns_map.get(prefix) if ns_map else None
            if prefix and not uri:
                raise ConverterError(f"Unknown namespace prefix: `{prefix}`")

        if " " in name or not namespaces.is_ncname(name):
            raise ConverterError

        return uri, name

deserialize(value, ns_map=None, **kwargs)

Convert a string value to QName instance.

The method supports strings with namespace prefixes or fully namespace qualified strings.

Examples:

  • xs:string -> QName("http://www.w3.org/2001/XMLSchema", "string")
  • {foo}bar -> QName("foo", "bar"

Parameters:

Name Type Description Default
value str

The input str value

required
ns_map Optional[Dict]

A namespace prefix-URI map

None
**kwargs Any

Unused keyword arguments

{}

Returns:

Type Description
QName

A QName instance

Raises:

Type Description
ConverterError

If the prefix can't be resolved.

Source code in xsdata/formats/converter.py
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
def deserialize(
    self,
    value: str,
    ns_map: Optional[Dict] = None,
    **kwargs: Any,
) -> QName:
    """Convert a string value to QName instance.

    The method supports strings with namespace prefixes
    or fully namespace qualified strings.

    Examples:
        - xs:string -> QName("http://www.w3.org/2001/XMLSchema", "string")
        - {foo}bar -> QName("foo", "bar"

    Args:
        value: The input str value
        ns_map: A namespace prefix-URI map
        **kwargs: Unused keyword arguments

    Returns:
        A QName instance

    Raises:
        ConverterError: If the prefix can't be resolved.
    """
    self.validate_input_type(value, str)
    namespace, tag = self.resolve(value, ns_map)

    return QName(namespace, tag) if namespace else QName(tag)

serialize(value, ns_map=None, **kwargs)

Convert a QName instance value sto string.

Convert a QName instance to string either with a namespace prefix if a prefix-URI namespaces mapping is provided or to a fully qualified name with the namespace.

Examples:

  • QName("http://www.w3.org/2001/XMLSchema", "int") & ns_map -> xs:int
  • QName("foo, "bar") -> {foo}bar

Parameters:

Name Type Description Default
value QName

The qname instance to convert

required
ns_map Optional[Dict]

A namespace prefix-URI map, if we want to use prefixes

None
**kwargs Any

Unused keyword arguments

{}

Returns:

Type Description
str

The str converted value.

Source code in xsdata/formats/converter.py
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
def serialize(
    self,
    value: QName,
    ns_map: Optional[Dict] = None,
    **kwargs: Any,
) -> str:
    """Convert a QName instance value sto string.

    Convert a QName instance to string either with a namespace prefix if a
    prefix-URI namespaces mapping is provided or to a fully qualified name
    with the namespace.

    Examples:
        - QName("http://www.w3.org/2001/XMLSchema", "int") & ns_map -> xs:int
        - QName("foo, "bar") -> {foo}bar

    Args:
        value: The qname instance to convert
        ns_map: A namespace prefix-URI map, if we want to use prefixes
        **kwargs: Unused keyword arguments

    Returns:
        The str converted value.
    """
    if ns_map is None:
        return value.text

    namespace, tag = namespaces.split_qname(value.text)

    if not namespace:
        return tag

    prefix = namespaces.load_prefix(namespace, ns_map)

    return f"{prefix}:{tag}" if prefix else tag

resolve(value, ns_map=None) staticmethod

Split a qname or ns prefixed string value or a uri, name pair.

Parameters:

Name Type Description Default
value str

the input value to resolve

required
ns_map Optional[Dict]

A namespace prefix-URI map

None

Returns:

Type Description
Tuple[str, str]

A tuple of uri and name strings.

Raises:

Type Description
ConverterError

if the uri is not valid, if the prefix can't be resolved to a URI, if the name is not a valid NCName

Source code in xsdata/formats/converter.py
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
@staticmethod
def resolve(value: str, ns_map: Optional[Dict] = None) -> Tuple[str, str]:
    """Split a qname or ns prefixed string value or a uri, name pair.

    Args:
        value: the input value to resolve
        ns_map: A namespace prefix-URI map

    Returns:
        A tuple of uri and name strings.

    Raises:
        ConverterError: if the uri is not valid,
            if the prefix can't be resolved to a URI,
            if the name is not a valid NCName
    """
    value = value.strip()

    if not value:
        raise ConverterError

    if value[0] == "{":
        uri, name = text.split(value[1:], "}")

        if not namespaces.is_uri(uri):
            raise ConverterError
    else:
        prefix, name = text.split(value, ":")
        uri = ns_map.get(prefix) if ns_map else None
        if prefix and not uri:
            raise ConverterError(f"Unknown namespace prefix: `{prefix}`")

    if " " in name or not namespaces.is_ncname(name):
        raise ConverterError

    return uri, name

EnumConverter

Bases: Converter

An enum converter.

Source code in xsdata/formats/converter.py
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
class EnumConverter(Converter):
    """An enum converter."""

    def serialize(self, value: Enum, **kwargs: Any) -> str:
        """Convert an enum member to a string."""
        return converter.serialize(value.value, **kwargs)

    def deserialize(
        self,
        value: Any,
        data_type: Optional[EnumMeta] = None,
        **kwargs: Any,
    ) -> Enum:
        """Convert a value to an enum member.

        Args:
            value: The input value
            data_type: The enumeration class
            **kwargs: Additional keyword arguments needed
                for parsing the value to a python type.

        Returns:
            The enum member.

        Raises:
            ConverterError: if the data type is not an enum, or the value
                doesn't match any of the enum members.
        """
        if data_type is None or not isinstance(data_type, EnumMeta):
            raise ConverterError(f"'{data_type}' is not an enum")

        if collections.is_array(value):
            values = value
        elif isinstance(value, str):
            value = value.strip()
            values = value.split()
        else:
            values = [value]

        length = len(values)
        for member in cast(Type[Enum], data_type):
            if self.match(value, values, length, member.value, **kwargs):
                return member

        raise ConverterError

    @classmethod
    def match(
        cls,
        value: Any,
        values: Sequence,
        length: int,
        real: Any,
        **kwargs: Any,
    ) -> bool:
        """Match a value to one of the enumeration values.

        Args:
            value: The input value
            values: The input value as a sequence, in case of NMTokens
            length: The length of the sequence values
            real: The enumeration value
            **kwargs: Additional keyword arguments needed
                for parsing the value to a python type.

        Returns:
            Whether the value or values matches the enumeration member value.
        """
        if isinstance(value, str) and isinstance(real, str):
            return value == real or " ".join(values) == real

        if isinstance(real, (tuple, list)) and not hasattr(real, "_fields"):
            if len(real) == length and cls._match_list(values, real, **kwargs):
                return True
        elif length == 1 and cls._match_atomic(value, real, **kwargs):
            return True

        return False

    @classmethod
    def _match_list(cls, raw: Sequence, real: Sequence, **kwargs: Any) -> bool:
        for index, val in enumerate(real):
            if not cls._match_atomic(raw[index], val, **kwargs):
                return False

        return True

    @classmethod
    def _match_atomic(cls, raw: Any, real: Any, **kwargs: Any) -> bool:
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            cmp = converter.deserialize(raw, [type(real)], **kwargs)

        if isinstance(real, float):
            return cmp == real or repr(cmp) == repr(real)

        return cmp == real

serialize(value, **kwargs)

Convert an enum member to a string.

Source code in xsdata/formats/converter.py
615
616
617
def serialize(self, value: Enum, **kwargs: Any) -> str:
    """Convert an enum member to a string."""
    return converter.serialize(value.value, **kwargs)

deserialize(value, data_type=None, **kwargs)

Convert a value to an enum member.

Parameters:

Name Type Description Default
value Any

The input value

required
data_type Optional[EnumMeta]

The enumeration class

None
**kwargs Any

Additional keyword arguments needed for parsing the value to a python type.

{}

Returns:

Type Description
Enum

The enum member.

Raises:

Type Description
ConverterError

if the data type is not an enum, or the value doesn't match any of the enum members.

Source code in xsdata/formats/converter.py
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
def deserialize(
    self,
    value: Any,
    data_type: Optional[EnumMeta] = None,
    **kwargs: Any,
) -> Enum:
    """Convert a value to an enum member.

    Args:
        value: The input value
        data_type: The enumeration class
        **kwargs: Additional keyword arguments needed
            for parsing the value to a python type.

    Returns:
        The enum member.

    Raises:
        ConverterError: if the data type is not an enum, or the value
            doesn't match any of the enum members.
    """
    if data_type is None or not isinstance(data_type, EnumMeta):
        raise ConverterError(f"'{data_type}' is not an enum")

    if collections.is_array(value):
        values = value
    elif isinstance(value, str):
        value = value.strip()
        values = value.split()
    else:
        values = [value]

    length = len(values)
    for member in cast(Type[Enum], data_type):
        if self.match(value, values, length, member.value, **kwargs):
            return member

    raise ConverterError

match(value, values, length, real, **kwargs) classmethod

Match a value to one of the enumeration values.

Parameters:

Name Type Description Default
value Any

The input value

required
values Sequence

The input value as a sequence, in case of NMTokens

required
length int

The length of the sequence values

required
real Any

The enumeration value

required
**kwargs Any

Additional keyword arguments needed for parsing the value to a python type.

{}

Returns:

Type Description
bool

Whether the value or values matches the enumeration member value.

Source code in xsdata/formats/converter.py
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
@classmethod
def match(
    cls,
    value: Any,
    values: Sequence,
    length: int,
    real: Any,
    **kwargs: Any,
) -> bool:
    """Match a value to one of the enumeration values.

    Args:
        value: The input value
        values: The input value as a sequence, in case of NMTokens
        length: The length of the sequence values
        real: The enumeration value
        **kwargs: Additional keyword arguments needed
            for parsing the value to a python type.

    Returns:
        Whether the value or values matches the enumeration member value.
    """
    if isinstance(value, str) and isinstance(real, str):
        return value == real or " ".join(values) == real

    if isinstance(real, (tuple, list)) and not hasattr(real, "_fields"):
        if len(real) == length and cls._match_list(values, real, **kwargs):
            return True
    elif length == 1 and cls._match_atomic(value, real, **kwargs):
        return True

    return False

DateTimeBase

Bases: Converter

An abstract datetime converter.

Source code in xsdata/formats/converter.py
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
class DateTimeBase(Converter, metaclass=abc.ABCMeta):
    """An abstract datetime converter."""

    @classmethod
    def parse(cls, value: Any, **kwargs: Any) -> datetime:
        """Parse a str into a datetime instance.

        Args:
            value: The input string value
            **kwargs: Additional keyword argument
                format: The datetime format to use

        Returns:
            The datetime instance

        Raises:
            ConverterError: If no format was provided or the value
                could not be converted.
        """
        try:
            return datetime.strptime(value, kwargs["format"])
        except KeyError:
            raise ConverterError("Missing format keyword argument")
        except Exception as e:
            raise ConverterError(e)

    def serialize(self, value: Union[date, time], **kwargs: Any) -> str:
        """Convert a datetime instance to string.

        Args:
            value: The input datetime instance
            **kwargs: Additional keyword argument
                format: The datetime format to use

        Returns:
            The converted str value.

        Raises:
            ConverterError: If no format was provided or the value
                could not be converted.
        """
        try:
            return value.strftime(kwargs["format"])
        except KeyError:
            raise ConverterError("Missing format keyword argument")
        except Exception as e:
            raise ConverterError(e)

    @abc.abstractmethod
    def deserialize(self, value: Any, **kwargs: Any) -> Any:
        """Parse string literal value into python."""

parse(value, **kwargs) classmethod

Parse a str into a datetime instance.

Parameters:

Name Type Description Default
value Any

The input string value

required
**kwargs Any

Additional keyword argument format: The datetime format to use

{}

Returns:

Type Description
datetime

The datetime instance

Raises:

Type Description
ConverterError

If no format was provided or the value could not be converted.

Source code in xsdata/formats/converter.py
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
@classmethod
def parse(cls, value: Any, **kwargs: Any) -> datetime:
    """Parse a str into a datetime instance.

    Args:
        value: The input string value
        **kwargs: Additional keyword argument
            format: The datetime format to use

    Returns:
        The datetime instance

    Raises:
        ConverterError: If no format was provided or the value
            could not be converted.
    """
    try:
        return datetime.strptime(value, kwargs["format"])
    except KeyError:
        raise ConverterError("Missing format keyword argument")
    except Exception as e:
        raise ConverterError(e)

serialize(value, **kwargs)

Convert a datetime instance to string.

Parameters:

Name Type Description Default
value Union[date, time]

The input datetime instance

required
**kwargs Any

Additional keyword argument format: The datetime format to use

{}

Returns:

Type Description
str

The converted str value.

Raises:

Type Description
ConverterError

If no format was provided or the value could not be converted.

Source code in xsdata/formats/converter.py
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
def serialize(self, value: Union[date, time], **kwargs: Any) -> str:
    """Convert a datetime instance to string.

    Args:
        value: The input datetime instance
        **kwargs: Additional keyword argument
            format: The datetime format to use

    Returns:
        The converted str value.

    Raises:
        ConverterError: If no format was provided or the value
            could not be converted.
    """
    try:
        return value.strftime(kwargs["format"])
    except KeyError:
        raise ConverterError("Missing format keyword argument")
    except Exception as e:
        raise ConverterError(e)

deserialize(value, **kwargs) abstractmethod

Parse string literal value into python.

Source code in xsdata/formats/converter.py
759
760
761
@abc.abstractmethod
def deserialize(self, value: Any, **kwargs: Any) -> Any:
    """Parse string literal value into python."""

TimeConverter

Bases: DateTimeBase

A datetime.time converter.

Source code in xsdata/formats/converter.py
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
class TimeConverter(DateTimeBase):
    """A datetime.time converter."""

    def deserialize(self, value: Any, **kwargs: Any) -> time:
        """Convert the input str to a time instance.

        Args:
            value: The input string value
            **kwargs: Additional keyword argument
                format: The time format to use

        Returns:
            The time instance

        Raises:
            ConverterError: If no format was provided or the value
                could not be converted.
        """
        return self.parse(value, **kwargs).time()

deserialize(value, **kwargs)

Convert the input str to a time instance.

Parameters:

Name Type Description Default
value Any

The input string value

required
**kwargs Any

Additional keyword argument format: The time format to use

{}

Returns:

Type Description
time

The time instance

Raises:

Type Description
ConverterError

If no format was provided or the value could not be converted.

Source code in xsdata/formats/converter.py
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
def deserialize(self, value: Any, **kwargs: Any) -> time:
    """Convert the input str to a time instance.

    Args:
        value: The input string value
        **kwargs: Additional keyword argument
            format: The time format to use

    Returns:
        The time instance

    Raises:
        ConverterError: If no format was provided or the value
            could not be converted.
    """
    return self.parse(value, **kwargs).time()

DateConverter

Bases: DateTimeBase

A datetime.date converter.

Source code in xsdata/formats/converter.py
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
class DateConverter(DateTimeBase):
    """A datetime.date converter."""

    def deserialize(self, value: Any, **kwargs: Any) -> date:
        """Convert the input str to a date instance.

        Args:
            value: The input string value
            **kwargs: Additional keyword argument
                format: The time format to use

        Returns:
            The date instance

        Raises:
            ConverterError: If no format was provided or the value
                could not be converted.
        """
        return self.parse(value, **kwargs).date()

deserialize(value, **kwargs)

Convert the input str to a date instance.

Parameters:

Name Type Description Default
value Any

The input string value

required
**kwargs Any

Additional keyword argument format: The time format to use

{}

Returns:

Type Description
date

The date instance

Raises:

Type Description
ConverterError

If no format was provided or the value could not be converted.

Source code in xsdata/formats/converter.py
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
def deserialize(self, value: Any, **kwargs: Any) -> date:
    """Convert the input str to a date instance.

    Args:
        value: The input string value
        **kwargs: Additional keyword argument
            format: The time format to use

    Returns:
        The date instance

    Raises:
        ConverterError: If no format was provided or the value
            could not be converted.
    """
    return self.parse(value, **kwargs).date()

DateTimeConverter

Bases: DateTimeBase

A datetime.datetime converter.

Source code in xsdata/formats/converter.py
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
class DateTimeConverter(DateTimeBase):
    """A datetime.datetime converter."""

    def deserialize(self, value: Any, **kwargs: Any) -> datetime:
        """Convert the input str to a datetime instance.

        Args:
            value: The input string value
            **kwargs: Additional keyword argument
                format: The time format to use

        Returns:
            The datetime instance

        Raises:
            ConverterError: If no format was provided or the value
                could not be converted.
        """
        return self.parse(value, **kwargs)

deserialize(value, **kwargs)

Convert the input str to a datetime instance.

Parameters:

Name Type Description Default
value Any

The input string value

required
**kwargs Any

Additional keyword argument format: The time format to use

{}

Returns:

Type Description
datetime

The datetime instance

Raises:

Type Description
ConverterError

If no format was provided or the value could not be converted.

Source code in xsdata/formats/converter.py
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
def deserialize(self, value: Any, **kwargs: Any) -> datetime:
    """Convert the input str to a datetime instance.

    Args:
        value: The input string value
        **kwargs: Additional keyword argument
            format: The time format to use

    Returns:
        The datetime instance

    Raises:
        ConverterError: If no format was provided or the value
            could not be converted.
    """
    return self.parse(value, **kwargs)

ProxyConverter

Bases: Converter

Proxy wrapper to treat callables as converters.

Parameters:

Name Type Description Default
factory Callable

The callable factory

required
Source code in xsdata/formats/converter.py
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
class ProxyConverter(Converter):
    """Proxy wrapper to treat callables as converters.

    Args:
        factory: The callable factory
    """

    __slots__ = "factory"

    def __init__(self, factory: Callable):
        self.factory = factory

    def deserialize(self, value: Any, **kwargs: Any) -> Any:
        """Call the instance factory and return the result.

        Args:
            value: The input value to convert
            **kwargs: Unused keyword arguments

        Returns:
            The return result of the callable.

        Raises:
            ConverterError: on value errors.
        """
        try:
            return self.factory(value)
        except ValueError as e:
            raise ConverterError(e)

    def serialize(self, value: Any, **kwargs: Any) -> str:
        """Cast value to str."""
        return str(value)

deserialize(value, **kwargs)

Call the instance factory and return the result.

Parameters:

Name Type Description Default
value Any

The input value to convert

required
**kwargs Any

Unused keyword arguments

{}

Returns:

Type Description
Any

The return result of the callable.

Raises:

Type Description
ConverterError

on value errors.

Source code in xsdata/formats/converter.py
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
def deserialize(self, value: Any, **kwargs: Any) -> Any:
    """Call the instance factory and return the result.

    Args:
        value: The input value to convert
        **kwargs: Unused keyword arguments

    Returns:
        The return result of the callable.

    Raises:
        ConverterError: on value errors.
    """
    try:
        return self.factory(value)
    except ValueError as e:
        raise ConverterError(e)

serialize(value, **kwargs)

Cast value to str.

Source code in xsdata/formats/converter.py
857
858
859
def serialize(self, value: Any, **kwargs: Any) -> str:
    """Cast value to str."""
    return str(value)