python-attrs / python-attrs/cattrs

Union disambiguation fails when using `to_camel` structuring/unstructuring hook factories

Open
#233 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
1.1k
Forks
159
Avg merge
12h 21m
Merged PRs (30d)
6

Description

  • cattrs version: 1.10.0
  • Python version: 3.8.10
  • Operating System: Ubuntu:20.04
Description

Consider the following:


@define
class A:
    first_field: int
    second_field: int

@define
class B:
    first_field: int
    third_Field: int

Using the hook factories described here to structure/unstructure camelCase attributes:

converter = Converter()

def to_camel_case(snake_str: str) -> str:
....
converter.register_structure_hook_factory(
    has, to_camel_case_structure
)

Then the following behavior is observed:

camel_case_dict = {
    "thirdField": 2,
    "firstField": 1
}

The following works:

 converter.structure(camel_case_dict, Union[A, B])
 converter.structure(camel_case_dict, Union[B, A])

However, if we structure using Union[B, A] first, then cattrs tries to structure the input as A instead of B:

 converter.structure(camel_case_dict, Union[B, A])
o = {'firstField': 1, 'thirdField': 2}
_ = (<class 'test.input_config.test_output_config.A'>,)

    def structure_A(o, *_):
      res = {
        'first_field': structure_first_field(o['firstField'], type_first_field),
>       'second_field': structure_second_field(o['secondField'], type_second_field),
        }
E     KeyError: 'secondField'

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 running the reproducer from the issue with the camelCase hook factories and both Union orderings. Trace the union disambiguation and generated structuring path, then add a regression test showing that structuring Union[B, A] works regardless of which union order is used and no missing-field KeyError occurs.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend-api-design
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.