feat: add InputTypesMap and _instantiate_input function (#2955)

* refactor: add _input_type attribute to dump in BaseInputMixin

* feat: add InputTypesMap and _instantiate_input function

The commit adds the `InputTypesMap` dictionary and `_instantiate_input` function to the `inputs.py` file. The `InputTypesMap` is a dictionary that maps input types to their corresponding classes, and the `_instantiate_input` function is used to instantiate an input object based on its type. This change improves the flexibility and extensibility of the codebase.
This commit is contained in:
Gabriel Luiz Freitas Almeida 2024-07-25 14:09:12 -03:00 committed by GitHub
commit dea322b024
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 12 additions and 1 deletions

View file

@ -87,6 +87,7 @@ class BaseInputMixin(BaseModel, validate_assignment=True):
dump = handler(self)
if "field_type" in dump:
dump["type"] = dump.pop("field_type")
dump["_input_type"] = self.__class__.__name__
return dump

View file

@ -1,4 +1,4 @@
from typing import Any, AsyncIterator, Iterator, Optional, Union
from typing import Any, AsyncIterator, Iterator, Optional, Union, get_args
from loguru import logger
from pydantic import Field, field_validator
@ -360,3 +360,13 @@ InputTypes = Union[
MessageInput,
TableInput,
]
InputTypesMap: dict[str, type[InputTypes]] = {t.__name__: t for t in get_args(InputTypes)}
def _instantiate_input(input_type: str, data: dict) -> InputTypes:
input_type_class = InputTypesMap.get(input_type)
if input_type_class:
return input_type_class(**data)
else:
raise ValueError(f"Invalid input type: {input_type}")