pythonpython-typingpydanticpython-dataclasses

Creating a custom Python type from existing dataclass / pydandic class


I have a kind of standard response format I want to apply to all my fastAPI responses. For this example, we'll talk about something like this:

@dataclass
class Response:
    status: str = "OK"
    data: Any

Where the data can be any other dataclass. However, I don't want to have to create a separate dataclass for each. In my dreams, I'd love to have the option to do something like

@dataclass
class Customer:
    name: str
    age: int

@app.get()
def get_customer(customer_id) -> Response[Customer]
    ....

Is there any way for me to do this in Python? Create these kind of custom types?

Thanks


Solution

  • There is a feature of pydantic for generic models: https://docs.pydantic.dev/latest/concepts/models/#generic-models

    See below:

    from typing import Generic, TypeVar
    from pydantic import BaseModel
    
    Data = TypeVar("Data")
    
    class Response(BaseModel, Generic[Data]):
        status: str = "OK"
        data: Data
    
    
    class Customer(BaseModel):
        name: str
        age: int
    
    CustomerResp = Response[Customer]