[Python] How can I extend an annotated type

Discussão em 'Python' iniciado por Stack, Maio 30, 2025.

  1. Stack

    Stack Membro Participativo

    I have a base type definition that I use in many models:


    Alpha = Annotated[str, Field(pattern=r'[A-Za-z]')]


    I want to create additional specialised types based on this type, for example by adding a max_length constraint. I want to do this in a declarative way, ideally using Annotated as the type definitions will be auto-generated into a module for import.

    This doesn't work, because it produces a nested annotation, but I'd like something like it:

    ShortAlpha = Annotated[Alpha, Field(max_length=5)]


    is there a way to extend Annotated type definitions without having to explicitly dig around in the original type's internals?

    Continue reading...

Compartilhe esta Página