Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

When parsing with Union Optional values are swallowing the input #263

Open
m-aciek opened this issue Oct 22, 2024 · 0 comments · May be fixed by #264
Open

When parsing with Union Optional values are swallowing the input #263

m-aciek opened this issue Oct 22, 2024 · 0 comments · May be fixed by #264
Labels
bug Something isn't working

Comments

@m-aciek
Copy link
Contributor

m-aciek commented Oct 22, 2024

Hi, thanks for your work on the library.

Describe the bug

When parsing with union an Optional value in a dataclass doesn't consider the existence of keys in dictionaries when parsing the structure. Please see the reproducer.

To Reproduce
Consider the code below:

from dataclasses import dataclass
from typing import Union, Optional

import dacite


@dataclass
class OptionalDataclass:
    optional: Optional[int]

@dataclass
class Required:
    required: int

@dataclass
class UnionDataclass:
    field: Union[OptionalDataclass, Required]


print(dacite.from_dict(UnionDataclass, {"field": {"required": 2}}))
# UnionDataclass(field=OptionalDataclass(optional=None))

Expected behavior

print(dacite.from_dict(UnionDataclass, {"field": {"required": 2}}))
# UnionDataclass(field=Required(required=2))

I would expect dacite to look into dictionary keys and prefer an object which has the key.

Environment

  • Python version: 3.9
  • dacite version: 1.8.1

Additional context

Changing the order of classes in the Union annotation helps in this case.

from dataclasses import dataclass
from typing import Union, Optional

import dacite


@dataclass
class OptionalDataclass:
    optional: Optional[int]

@dataclass
class Required:
    required: int

@dataclass
class UnionDataclass:
    field: Union[Required, OptionalDataclass]


print(dacite.from_dict(UnionDataclass, {"field": {"required": 2}}))
# UnionDataclass(field=Required(required=2))
@m-aciek m-aciek added the bug Something isn't working label Oct 22, 2024
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant