jangada.serialization.SerializableProperty.default#

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

Set a default value factory using decorator syntax.

The default factory is called when the property needs a default value (on first access or when explicitly set to None). It receives the instance as its argument and should return the default value.

Parameters:
funcDefaultCallable

Function that generates default values. Should accept one argument (the instance) and return the default value.

Returns:
Self

A new SerializableProperty instance with the default factory set.

Notes

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

Using a callable default is essential for mutable default values to avoid sharing state between instances (similar to avoiding mutable default arguments in function definitions).

Examples

>>> class Container:
...     items = SerializableProperty()
...
...     @items.default
...     def items(self):
...         return []  # New list for each instance
...
>>> c1 = Container()
>>> c2 = Container()
>>> c1.items.append(1)
>>> c2.items.append(2)
>>> c1.items
[1]
>>> c2.items
[2]

The default factory can access instance attributes:

>>> class Experiment:
...     trial_number = SerializableProperty(default=1)
...     data_file = SerializableProperty()
...
...     @data_file.default
...     def data_file(self):
...         return f"trial_{self.trial_number}.dat"
...
>>> exp = Experiment()
>>> exp.data_file
'trial_1.dat'