python-attrs / python-attrs/cattrs

Recent fix to orjson serialization breaks unions

Open
#248 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.dev0
  • Python version: 3.7
  • Operating System: Ubuntu 16.04
Description

Orjson doesn't like it when classes have union types as entries. It doesn't always happen, but it does in the case I'm actually working on.

What I Did

Unfortunately, I've been unable to come up with a small example for this one, but I can explain the error:

in orjson.py, there is the section:

        if args:
            if (issubclass(args[0], str) and issubclass(args[0], Enum)):

                def key_handler(v):
                    return v.value

I have managed to get args[0] to be a typing.Union type, which means that this crashes, since issubclass only works on type objects, and typing.Union is not a type object.

This can be fixed by changing it to

        if args:
            if (isinstance(args[0], type) and
                issubclass(args[0], str) and
                issubclass(args[0], Enum)):

                def key_handler(v):
                    return v.value

I suspect this might be the case in other converters as well, but since I'm using orjson, that's the one I ran into it in

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 in orjson.py at the key_handler setup where args[0] is checked with issubclass. Exercise the converter with a class containing a typing.Union entry, then verify that union types no longer trigger the issubclass failure while the existing string Enum handling still works.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.