-
Notifications
You must be signed in to change notification settings - Fork 112
Description
Describe the bug
After updating dacite to version 1.9.2, from_dict raises an AttributeError: Could not find reference when processing a dataclass that contains a Literal type hint with string values (e.g., Literal["value"]).
It appears that dacite is incorrectly attempting to "dereference" the string values inside the Literal—treating them as forward references to class names that need to be imported—rather than treating them as simple string values.
To Reproduce
from dataclasses import dataclass
from typing import Literal
from dacite import from_dict
@dataclass
class Example:
# The string "active" causes dacite to look for a class named "active"
status: Literal["active", "inactive"]
data = {"status": "active"}
# This causes a crash in dacite 1.9.2
result = from_dict(data_class=Example, data=data)
print(result)Traceback:
Traceback (most recent call last):
...
File ".../site-packages/dacite/core.py", line 53, in from_dict
data_class_hints = cache(get_concrete_type_hints)(data_class, localns=config.hashable_forward_references)
File ".../site-packages/dacite/generics.py", line 100, in get_concrete_type_hints
hints[key] = __concretize(hint, generics, data_class)
File ".../site-packages/dacite/generics.py", line 49, in __concretize
return __dereference(hint, data_class)
File ".../site-packages/dacite/generics.py", line 40, in __dereference
raise AttributeError("Could not find reference.")
AttributeError: Could not find reference.
Expected behavior
from_dict should correctly parse the data and instantiate the dataclass without attempting to import or dereference the string values defined within Literal.
Environment
- Python version: 3.9
daciteversion: 1.9.2
Additional context
The issue seems to stem from the logic in dacite.generics.__dereference. When it iterates over the arguments of a generic type (in this case Literal), it encounters the string 'active'. It assumes this string is a forward reference to a type/class and attempts to find it in the module scope. When it fails to find a class named active, it raises AttributeError.
A temporary workaround is monkeypatching dacite.generics.__dereference to return the type_name string when AttributeError is caught.