cattrs
cattrs copied to clipboard
Recent fix to orjson serialization breaks unions
- 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
Ugh, I've been bitten by the unsafe issubclass builtin in another project. I think the easiest solution is just to create our own is_subclass, which eats any exceptions and just returns false.