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

dacite.from_dict: NamedTuple type hook does not work with cast=[tuple] (regression from v1.7.0) #253

Open
idanmiara opened this issue Feb 1, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@idanmiara
Copy link

idanmiara commented Feb 1, 2024

Describe the bug
dacite.from_dict fails for a class containing a NamedTuple if you also set cast=[tuple] in your Config

To Reproduce
The following code runs fine with dacite==1.7.0 but fails on dacite==1.8.1.
If you omit cast=[tuple] from the Config it also works on 1.8.1

from dataclasses import dataclass
from typing import NamedTuple

import dacite


class Point(NamedTuple):
    x: float
    y: float

    @staticmethod
    def from_dict(data: dict[str, float]) -> 'Point':
        return Point(data['x'], data['y'])


@dataclass
class Model:
    point: Point


type_hooks = {Point: lambda x: Point.from_dict(x)}
pd0 = dict(y=1.1, x=2.2)
d = {
    'point': pd0,
}
config = dacite.Config(type_hooks=type_hooks, cast=[tuple])
model1 = dacite.from_dict(Model, d, config=config)
model2 = Model(point=Point(**pd0))
assert model1 == model2
Traceback (most recent call last):
  File "/Users/idan.miara/Library/Application Support/JetBrains/PyCharm2023.2/scratches/scratch_161.py", line 27, in <module>
    model1 = dacite.from_dict(Model, d, config=config)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/idan.miara/.pyenv/versions/dacite/lib/python3.11/site-packages/dacite/core.py", line 64, in from_dict
    value = _build_value(type_=field_type, data=field_data, config=config)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/idan.miara/.pyenv/versions/dacite/lib/python3.11/site-packages/dacite/core.py", line 105, in _build_value
    data = type_(data)
           ^^^^^^^^^^^
TypeError: Point.__new__() missing 1 required positional argument: 'y'

Expected behavior

The code above should work fine as it did with 1.7.0

Environment

  • Python version: 3.11
  • dacite version: 1.8.1 (regression from 1.7.0)
@idanmiara idanmiara added the bug Something isn't working label Feb 1, 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

No branches or pull requests

1 participant