konradhalas / dacite

Simple creation of data classes from dictionaries.
MIT License
1.76k stars 106 forks source link

DataClass created with make_dataclass fails from_dict #127

Closed martin0 closed 3 years ago

martin0 commented 3 years ago

` from typing import Type, Any, Optional, Union, Collection, TypeVar, Dict, Callable, Mapping, List, Tuple from dataclasses import make_dataclass, dataclass from dacite import from_dict

@dataclass class User: name: str age: int is_active: bool

data = { 'name': 'John', 'age': 30, 'is_active': True, }

User2 = make_dataclass('User2', ['name','age','is_active'] ) user2 = from_dict(data_class=User2, data=data)`

error is Exception has occurred: ForwardReferenceError can not resolve forward reference: name 'typing' is not defined

konradhalas commented 3 years ago

hi @martin0 - thank you for reporting this issue.

I see that you do not pass type information in make_dataclass which creates following data class:

@dataclass
class User:
    name: "typing.Any"
    age: "typing.Any"
    is_active: "typing.Any"

I don't know why this type info is passed as a forward reference but because this is very rare case I don't want to "fix" it in dacite.

If you want to fix on your side, you have to use Config(forward_references={"typing": typing}).

import typing
from dataclasses import make_dataclass, dataclass
from dacite import from_dict, Config

data = {
    "name": "John",
    "age": 30,
    "is_active": True,
}

User = make_dataclass("User2", ["name", "age", "is_active"])
user = from_dict(data_class=User, data=data, config=Config(forward_references={"typing": typing}))