python-attrs / python-attrs/attrs

Pass the attribute name to the converter? (3 arg converters)

Open
#1,108 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
5.8k
Forks
480
Avg merge
2h 15m
Merged PRs (30d)
2

Description

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)
    

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the current converter API and its tests to determine how converters receive values and how attribute metadata is available. Compare the proposed three-argument converter behavior with existing converter forms and document the compatibility constraints. Done means the supported API and resulting validation error behavior are specified and covered by tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.