[Python] Python Typing: Put Constraint on Annotated

Discussão em 'Python' iniciado por Stack, Março 18, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to do some meta-programming with python type annotations.

    I want to define a certain type of Annotated, constraining the type for the metadata of the Annotated special form.

    For example, I want to write a function, which only allows for Annotated types whose first metadata entry is a tuple:

    from typing import Annotated

    PositiveIntWithExamples = Annotated[int, (12, 1001)]
    Bad = Annotated[int, "This is bad."]

    def extract_examples(annotated_type: "AnnotatedWithExamples") -> tuple:
    return annotated_type.__metadata__[0]

    extract_examples(PositiveInt)
    extract_examples(Bad) # typechecker should alert here


    In the example above, how would I have to define AnnotatedWithExamples?

    I think it might be possible to achieve this with a mypy plugin, and bake the structure of AnnotatedWithExamples into the plugin. But is it possible to do this within the python typing system?

    I don't think I can do this either with Annotated, or something equivalent with NewType, or can I?

    Continue reading...

Compartilhe esta Página