Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

...
### Fixed

- Require matching value types when checking `Literal` fields, distinguishing equal boolean, integer, and enum values.

## [1.9.2] - 2025-02-05

Expand Down
2 changes: 1 addition & 1 deletion dacite/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def is_instance(value: Any, type_: Type) -> bool:
if is_new_type(type_):
return is_instance(value, extract_new_type(type_))
if is_literal(type_):
return value in extract_generic(type_)
return any(type(value) is type(literal) and value == literal for literal in extract_generic(type_))
if is_init_var(type_):
return is_instance(value, extract_init_var(type_))
if is_type_generic(type_):
Expand Down
24 changes: 24 additions & 0 deletions tests/core/test_literal.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from dataclasses import dataclass
from enum import IntEnum
from typing import Optional

import pytest
Expand Down Expand Up @@ -57,3 +58,26 @@ class X:
result = from_dict(X, {"l": "A"})

assert result == X(l="A")


class Number(IntEnum):
ONE = 1


@literal_support
@pytest.mark.parametrize(
"literal, value", [(1, True), (True, 1), (0, False), (False, 0), (1, 1.0), (Number.ONE, 1), (1, Number.ONE)]
)
def test_from_dict_with_equal_literal_of_wrong_type(literal, value):
from typing import Literal

@dataclass
class X:
l: Literal[literal]

with pytest.raises(WrongTypeError):
from_dict(X, {"l": value})

result = from_dict(X, {"l": literal})
assert result.l == literal
assert type(result.l) is type(literal)