'Factory for Generic types
I guess most Python lovers know it but, in order to provide some context, the typing module provides a mechanism for defining type hints as follows:
from typing import List
x = List[int]
In the code above, x represents a List whose items are integers.
In the scope of microservices, FastAPI library allows defining the endpoint argument types through the use of Pydantic library.
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
friends: List[int] = []
I am trying to generate an endpoint for a ML model without knowing its input format. My approach is to extract is metadata and see the input schema, and generate a Pydantic class from it.
My question is...
Is there a way of programmatically obtaining get a type like those referenced by x, so I can implement a factory for generating them based on some input?
Solution 1:[1]
You can create your own generic class:
from pydantic import GenericModel
from typing import Generic, TypeVar
F = TypeVar("F")
class User(GenericModel, Generic[F]):
id: int
name: str
friends: List[F]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
