[Python] Pydantic v2 + Python 3.13: PEP 695 type-alias of a generic model returns...

Discussão em 'Python' iniciado por Stack, Junho 22, 2025.

  1. Stack

    Stack Membro Participativo

    I’m experimenting with Python 3.13 and Pydantic v2.11.7. My goal is to avoid writing

    GenericTraining[Discriminate[L1LossConfig]]


    over and over—I’d like a terse alias such that I can do

    TrainingLike[L1LossConfig]


    and still have a fully-fledged BaseModel subclass (with Pydantic’s model_rebuild, validators, etc.).

    Minimal reproducible example

    from typing import Annotated, Literal
    from pydantic import BaseModel, Field


    class L1LossConfig(BaseModel):
    loss_type: Literal["l1"] = "l1"


    class GenericTraining[LossT](BaseModel):
    loss: LossT


    type Discriminate[T] = Annotated[T, Field(discriminator="loss_type")]

    # -----------------------------------------------------------------------------
    # 1️⃣ VERBOSE version – works
    Training1 = GenericTraining[Discriminate[L1LossConfig]]
    Training1.model_rebuild() # ✅ OK

    # 2️⃣ TERSE version – breaks
    type TrainingLike[T] = GenericTraining[Discriminate[T]]

    Training2 = TrainingLike[L1LossConfig]
    Training2.model_rebuild() # ❌ Attribute "model_rebuild" is unknown


    How can I have TrainingLike[L1LossConfig] behave exactly like GenericTraining[Discriminate[L1LossConfig]], i.e. to be a real subclass of BaseModel?

    Continue reading...

Compartilhe esta Página