attrs
attrs copied to clipboard
Pass the attribute name to the converter? (3 arg converters)
This is not a bug per se but more an improvement.
From my understanding, converters are passed only the value today. Would it be possible to pass the attribute name as well?
The motivation behind this is because as you try to convert/parse data in the converter, you end up adding some validation as well and it would be helpful to know for what attribute it is run for to have a better error message. (e.g.: f"{attribute} value cannot be converted to a date")
In the example below, the converter tries to convert the input into a date object. This can fail and it would make sense to raise a validation error at that point but it would help to know the attribute this is for.
Thoughts?
import attr
from datetime import date
def convert_to_date(value):
try:
dt_obj = ... # convert value
exception:
raise ValueError('Cannot convert to date') # would like f"{attribute} value cannot be converted to a date" instead
return dt_obj
@attr.s(kw_only=True)
class Params:
day1: date = attr.ib(converter=convert_to_date)
day2: date = attr.ib(converter=convert_to_date)
day3: date = attr.ib(converter=convert_to_date)
day4: date = attr.ib(converter=convert_to_date)
day5: date = attr.ib(converter=convert_to_date)
day6: date = attr.ib(converter=convert_to_date)
day7: date = attr.ib(converter=convert_to_date)
I think this could be a useful feature.
But I don't see another way than passing the attribute's name by hand. It should of course be possible to configure the converter callable to accept some parameters (if it doesn't work already, have you tried that?).
What do you mean "by hand"?
The validators are called with instance, attribute, value
by attrs
.
Could attrs
call the converters with the same or maybe without the instance?
At the moment, only the value
is passed to the converters.
I have started to work on three-arg converters before my vacation based on #404. But it’s a bit tricky to get it right without a performance penalty.
3 arg converters would be great, I'm often wanting to write generic converters that know the type of the attribute they need to convert to