Skip to content

Better support for primitive numeric types #222

@ltn100

Description

@ltn100

I'm not sure if dacite's primitive numeric type handling is by design, but it is not what I expected.

Here is an example:

import dacite
from dataclasses import dataclass


@dataclass
class A:
    x: int
    y: float
    z: complex


dubiously_typed_dict = {
    "x": 1,
    "y": 1,
    "z": 1,
}

a = dacite.from_dict(data_class=A, data=dubiously_typed_dict)

print(a)
# prints: A(x=1, y=1, z=1)
# note: all integer values

Even when we use Config(strict=True), no warning or error is produced.

In order to type cast these values as I expect, we need to do:

a = dacite.from_dict(data_class=A, data=dubiously_typed_dict, config=dacite.Config(cast=[float, int, complex]))

print(a)
# prints: A(x=1, y=1.0, z=(1+0j))

Perhaps it would be good to either:

  • Type cast primitive types by default; or
  • Type cast all types by default (is there any reason not to do this?); or
  • Raise an error if the incoming type is incorrect

An alternative solution may be to (ab)use some kind of sentinel to enable casting of all types:

Config(cast=[typing.Any])
Config(cast=[...])
Config(cast=[dacite.Any])
Config(cast=[dacite.Primitives])

or even a new option:

Config(cast_all=True)

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions