Skip to content

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

Closed

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?

Activity

  1. sobolevn commented on Mar 2, 2020

    @sobolevn
    Member

    Generic currently does not work that great. See #8

    I would recommend to use regular classes for this case. For now 🙂

  2. sobolevn commented on Jun 11, 2021

    @sobolevn
    Member

    Done! See #207

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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