wyfo / apischema

JSON (de)serialization, GraphQL and JSON schema generation using Python typing.

Home Page:https://wyfo.github.io/apischema/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Unions break depending on order

kevinheavey opened this issue · comments

I get an error when deserialising Union[Literal, MyClass] but not when deserialising Union[MyClass, Literal].
It seems this error started some time after v0.15.7.

Example:

from typing import Union, Literal
from dataclasses import dataclass
from apischema import deserialize


@dataclass
class Bar:
    baz: int


deserialize(Union[Literal["foo"], Bar], {"baz": 1})  # this fails
deserialize(Union[Bar, Literal["foo"]], {"baz": 1})  # this works

Here's the traceback for the the call that fails:

Traceback (most recent call last):
  File "/home/kheavey/anchorpy/throwaway.py", line 11, in <module>
    deserialize(Union[Literal["foo"], Bar], {"baz": 1})
  File "/home/kheavey/anchorpy/.venv/lib/python3.9/site-packages/apischema/utils.py", line 424, in wrapper
    return wrapped(*args, **kwargs)
  File "/home/kheavey/anchorpy/.venv/lib/python3.9/site-packages/apischema/deserialization/__init__.py", line 912, in deserialize
    return deserialization_method(
  File "/home/kheavey/anchorpy/.venv/lib/python3.9/site-packages/apischema/deserialization/__init__.py", line 698, in method
    return deserialize_alt(data)
  File "/home/kheavey/anchorpy/.venv/lib/python3.9/site-packages/apischema/deserialization/__init__.py", line 271, in method
    return value_map[data]
TypeError: unhashable type: 'dict'

Here's what value_map and data look like:

(Pdb) value_map
{'foo': 'foo'}
(Pdb) data
{'baz': 1}

Fixed in v0.16.3