Decorator for attrs converter

Viewed 1069

Is there a decorator for using attrs converters?

There are decorators for validator and default, but I couldn't see anything mentioned for converter.

Is it possible?

I prefer to have the function as a "method" within the class, as opposed to global function outside the class. Decorators allow that :)

example snippet for validator.

    payload : bytes = attr.ib( default=b'', on_setattr=attr.setters.validate )

    #! NOTE: using attrs validator as a property setter function.
    @payload.validator
    def payload_setter( self, attribute : attr.Attribute, value : bytes ) -> None :
        self.payload_length = len( value )

I want to do something similar using converters. Example to trim some input bytes to an upper bound.

    data : bytes = attr.ib( default=b'', on_setattr=attr.setters.converter )

    #! NOTE: using attrs converter as a property setter function.
    @data.converter
    def data_setter( self, attribute : attr.Attribute, value : bytes ) -> None :
        trimmed_value = value[:10]
        return trimmed_value
2 Answers

This is how I do it and it works well enough. However, I use attrs for very simple cases and I can't guarantee that this will behave in more complex cases.

def converter(attribute):
    def decorator(func):
        attribute.converter = func
        return staticmethod(func)
    return decorator


@attr.s
class MyAttrs:
    number = attr.ib()

    @converter(number):
    def _convert_to_int(value):
        return int(value)


>>> MyAttrs('0')
MyAttrs(number=0)
>>> MyAttrs(12.5)
MyAttrs(number=12)
Related