binobj.decorators module

Function and method decorators.

class ValidatorMethodWrapper(func: Callable[[Field[Any], Any], bool | None] | Callable[[Struct, Mapping[str, Any]], bool | None], field_names: Iterable[str])

Bases: object

A wrapper around a validator method for one or more fields.

Parameters:
  • func (callable) – The validator to invoke for the named fields.

  • field_names – An iterable of strings; the names of the fields to be validated by func. If None or the iterable is empty, this validator method should be used to validate the entire struct, not just a field.

validates(*field_names: str) Callable[[Callable[[Field[Any], Any], bool | None]], ValidatorMethodWrapper]

Mark a method as a validator for one or more fields.

@validates('foo', 'bar')
def validator(self, field, value):
    if value >= 10:
        raise ValidationError('%r must be in [0, 10).' % field.name,
                              field=field)
Parameters:

field_names – One or more names of fields that this validator should be activated for.

Warning

If you specify multiple validator methods, the order in which they execute is not guaranteed. If you need a specific ordering of checks, you must put them in the same function.

Note

Only functions and instance methods are supported. Class methods and static methods will cause a crash.

validates_struct(func: Callable[[Struct, Mapping[str, Any]], bool | None]) ValidatorMethodWrapper

Mark a method as a validator for the entire struct.

The method being decorated should take a single argument aside from self, the dict to validate. The validator is invoked right after it’s been loaded, or right before it’s dumped.

It’s highly inadvisable to modify the contents, because it’s easy to create invalid results. For example, if a struct has a field giving the length of the array and you change the length of that array, the length field won’t update to compensate. You must do that yourself.

Usage:

@validates_struct
def validator(self, struct_dict):
    if struct_dict['foo'] % 2 != 0:
        raise ValidationError("'foo' must be even", field='foo')

Note

Only functions and instance methods are supported. Class methods and static methods will cause a crash.