python-attrs / python-attrs/cattrs

Weird output while structuring unions with custom disambiguation function

Open
#267 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: 22.1.0
  • Python version: 3.9
Description

Thanks for this amazing library !!

I am trying to write disambiguation function to handle union type based on the default value of child class but got into weird error, also want to understand the correct way to do it with cattrs.


@define(kw_only=True)
class GenType:
    pass

@define(kw_only=True)
class TypeOne(GenType):
    id:Literal["A"] = "A"


@define(kw_only=True)
class TypeTwo(GenType):
   id:Literal["B"] = "B"

UniType = Union[TypeOne, TypeTwo]

@define(kw_only=True)
class Container:
    types: List[UniType]

def discriminate_model_types(value: typing.Any, _klass: typing.Type) -> UniType:
    # Write some logic to find the exact type !!, I was wondering if there is correct pythonic version to do this with cattrs.
    for child_cls in GenType.__subclasses__():
        if value["id"] == child_cls().id:
            return cattr.structure(value, child_cls)

def run_union_logic():
    json = {"types":[{"id":"A"}]}
    cattr.register_structure_hook(UniType, discriminate_model_types)
    obj =cattr.structure(json, Container)
    print(obj)

    json = {"id": "A"}
    obj = cattr.structure(json, TypeOne)
    print(obj)

#Prints following:
#Container(types=[TypeOne()]) --> I dont know why property 'id' is not populated here. 
#TypeOne(id='A') 


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 minimal example in the issue, especially run_union_logic and the registered UniType structure hook, then compare the Container result with direct TypeOne structuring. Determine why the union path omits the default id and establish the correct disambiguation behavior for the reported cattrs and Python versions.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.