I am trying to learn attrs and I have two questions. Please note that I am using the ATTRS library, not ATTR.
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!
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