konradhalas / dacite

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

Fix optional union with "None" value #47

Closed GreyZmeem closed 5 years ago

GreyZmeem commented 5 years ago

Currently, dacit correctly handles None value when a field has a type of Optional[Type] (which is expanded to Union[Type, NoneType]) by checking that union is optional and has two types: https://github.com/konradhalas/dacite/blob/ece070cc3c25e86634086db8ee4f2e45bdfe6fe5/dacite/core.py#L82

But when a field has a type of Optional[Union[Type, Type]] or Union[Type, Optional[Type]] (which will expand to Union[Type, Type, NoneType] in both cases), dacite raises UnionMatchError if value is None:

dacite.exceptions.UnionMatchError: can not match type "NoneType" to any type of "i" union: typing.Union[int, str, NoneType]

The reason for this error is that NoneType is removed from the list of checked types: https://github.com/konradhalas/dacite/blob/ece070cc3c25e86634086db8ee4f2e45bdfe6fe5/dacite/core.py#L81 I'm not sure what this check is for, but without it everything should work fine (at least all tests are green).

Added tests for specified cases

konradhalas commented 5 years ago

@GreyZmeem thank you man! TBH I have no idea why I'm filtering out this NoneType from the types list 🤷‍♂️ Your PR works like a charm. Thank you once again!