Search code examples
pythonpython-attrs

Create a customer converter and validator using ATTRS


I am trying to learn attrs and I have two questions. Please note that I am using the ATTRS library, not ATTR.

  1. How do I create a converter to change typ to uppercase? ---> I solved this question. The formula below is updated. :)
  2. How do I create a validator to ensure that typ is contained within a list?

I've tried many things on both, but to no avail. The documentation does not show how to make either a custom converter or validator- or, at least, I do not understand if it does.

from attrs import define, field, validators, setters
from datetime import datetime

@define(slots=True)
class Trans:
    acct:   int     = field(validator=validators.instance_of(int), converter=int)
    id:     int     = field(validator=validators.instance_of(int), converter=int)
    ts:     datetime= field(validator=validators.instance_of(datetime))
    typ:    str     = field(converter=(lambda x: x.upper()))

@typ.validator   # this does not work
def typCheck(self, attrib, val):
    if val not in ['A','B','W']:
        raise ValueError('Must be one of these options: ' + str(typs))

a = Trans(1,1,utc,'w')

Thank you in advance!


Solution

  • For whomever needs it, here is the answer.

    from attrs import define, field, validators, setters
    from datetime import datetime
    
    typs = ['O', 'D', 'W', 'C']
    
    @define(slots=True)
    class Trans:
        acct:   int     = field(validator=validators.instance_of(int), converter=int)
        id:     int     = field(validator=validators.instance_of(int), converter=int)
        ts:     datetime= field(validator=validators.instance_of(datetime))
        typ:    str     = field(converter=(lambda x: x.upper()))
    
        @typ.validator
        def typCheck(self, attrib, val):
            if val not in typs:
                raise ValueError('Must be one of these options: ' + str(typs))
    
    a = Trans(1,1,utc,'w')
    a