konradhalas / dacite

Simple creation of data classes from dictionaries.
MIT License
1.72k stars 106 forks source link

Different behavior when using `Optional[Union[...]]` vs `Union[...]` #176

Closed scnerd closed 1 year ago

scnerd commented 2 years ago

I get some odd results when using an Optional[Union[...]] type when a regular Union[...] works great.

from dataclasses import dataclass
from typing import Optional, Union, List

import dacite

@dataclass
class A:
    x: str

@dataclass
class B:
    y: Optional[Union[List[A], A]]

dacite.from_dict(B, {'y': 'lol'}, config=dacite.Config(cast=[A]))
# B(y=A(x='lol'))  <-- correct
dacite.from_dict(B, {'y': ['lol']}, config=dacite.Config(cast=[A]))
# B(y=[A(x=A(x='lol'))])  <-- incorrect

This bug doesn't arise if Optional is omitted:

@dataclass
class B:
    y: Union[List[A], A]

dacite.from_dict(B, {'y': 'lol'}, config=dacite.Config(cast=[A]))
# B(y=A(x='lol'))
dacite.from_dict(B, {'y': ['lol']}, config=dacite.Config(cast=[A]))
# B(y=[A(x='lol')])

Versions:

scnerd commented 2 years ago

Same problem as #163 ?

konradhalas commented 1 year ago

@scnerd should be fixed now (https://github.com/konradhalas/dacite/pull/164)