Skip to content

How to implement conversion where return type is polymorphic? #36

Closed
@anatoly-scherbakov

Description

@anatoly-scherbakov

I am trying to implement a function which would deserialize arbitrary values from string representations. For example, I'd like to say

class Person(pydantic.BaseModel):
    name: str
    job: str

>>> from_json_string(Person, '{"name": "John Doe", "job": "baker"}')
Person(name='John Doe', job='baker')

Of course that requires an implementation for from_json_string, something like this:

T = TypeVar('T')

@from_json_string.instance(pydantic.BaseModel)
def pydantic_from_json_string(model_class: Type[T], raw_value: str) -> T:
    return model_class(**json.loads(raw_value))

I do not seem to be able to do this of course, since the library believes I am looking for instances of BaseModel whereas I am targeting the class itself.

@from_json_string.instance(Type[pydantic.BaseModel]) does not work because it does not match on generics.

Any workarounds?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions