Strictly Convert JSON dict to dataclass with enums at runtime

50 Views Asked by At

So, this actually does work:

from dataclasses import dataclass
from enum import Enum
from typing import Any, TypeVar

from pydantic import TypeAdapter, parse_obj_as

T = TypeVar('T')

def dict_to_dataclass_2(dict_: dict[Any, Any], dataclass_: type[T]) -> T:
    adapter = TypeAdapter(dataclass_)
    return adapter.validate_python(dict_)


class Color(Enum):
    RED = 'red'
    BLUE = 'blue'

@dataclass
class Fish:
    color: Color

dict_to_dataclass({'color': 'red'}, Fish)

But I'd like to pass strict=True to validate_python. Is there any way to pass that option, but still handle the enum conversion?

0

There are 0 best solutions below