jangada.serialization.SerializableProperty.parser#

SerializableProperty.parser(func: Callable[[object, Any], T]) Self#

Set a parser/validator function using decorator syntax.

The parser is called on every value set operation (including defaults) to validate, transform, or normalize the value before storage.

Parameters:
funcParser

Function to parse values. Should accept two arguments (instance and raw value) and return the parsed value.

Returns:
Self

A new SerializableProperty instance with the parser set.

Notes

This method creates a new descriptor instance rather than modifying the existing one.

Parsers are applied to: - Explicitly set values - Default values (both static and from factories) - Values set to None (after resolving to default)

If a parser raises an exception, it propagates to the caller and the property value is not changed.

Examples

Type conversion:

>>> class TypedProperty:
...     value = SerializableProperty()
...
...     @value.parser
...     def value(self, val):
...         return int(val)
...
>>> obj = TypedProperty()
>>> obj.value = "123"
>>> obj.value
123
>>> type(obj.value)
<class 'int'>

Validation:

>>> class PositiveNumber:
...     number = SerializableProperty(default=1)
...
...     @number.parser
...     def number(self, val):
...         val = float(val)
...         if val <= 0:
...             raise ValueError("Number must be positive")
...         return val
...
>>> obj = PositiveNumber()
>>> obj.number = 5
>>> obj.number = -1
Traceback (most recent call last):
    ...
ValueError: Number must be positive

Normalization:

>>> class Path:
...     directory = SerializableProperty()
...
...     @directory.parser
...     def directory(self, val):
...         import os
...         return os.path.abspath(os.path.expanduser(val))