[Python] Narrowing typing on a subclass

Discussão em 'Python' iniciado por Stack, Fevereiro 24, 2025.

  1. Stack

    Stack Membro Participativo

    I have a Pydantic class to represent how my general API response should look:

    class RootDataResponseSchema(BaseModel):
    status: Literal["success", "fail"]
    data: BaseModel


    I went with BaseModel for data, as the idea would be I'd subclass RootDataResponseSchema and add more specificity to specific endpoint responses, such as:

    class NewItemResponse(RootDataResponseSchema):
    status: Literal["success"] = "success"
    data: NewItemResponseData


    The problem I've run into seems to only affect the IDE (in my case VSCode), so I assume is a notice from pylance, but tells me that both status and data have changed from the root class. It does mention it's irrelevant, but as a subclassed object does count as the superclass in terms of comparison, is there a mechanism for narrowing the scope of type hints in Python? Or is this just an artifact of loosely typed Python?

    Continue reading...

Compartilhe esta Página