[Python] python type annotation of SpecialForms with pydantic and mypy

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

  1. Stack

    Stack Membro Participativo

    python 3.13 pydantic 2.10.5 mypy 1.16.0

    how to properly annotate return of typing._SpecialForm, specifically typing.Annotated? I'm using mypy as type checker.

    from functools import partial
    from typing import Annotated

    from pydantic import AfterValidator, BaseModel


    def validate_smth(value: str, context: str) -> str:
    if value == "test":
    print(f"Validated {value}")
    else:
    raise ValueError(f"Value {value} is not allowed in context {context}")
    return value


    def return_annotated_type(context: str = "") -> type: # error: Incompatible return value type (got "<typing special form>", expected "type") [return-value]
    validator = partial(validate_smth, context=context)
    return Annotated[str, AfterValidator(validator)]


    class MyModel(BaseModel):
    field: return_annotated_type(context="test") # error: Invalid type comment or annotation [valid-type]
    # note: Suggestion: use return_annotated_type[...] instead of return_annotated_type(...)

    MyModel.model_validate({"field": "test"})



    I tried:

    def return_annotated_type(context: str = "") -> Annotated[str, AfterValidator]:
    # error: Incompatible return value type (got "<typing special form>", expected "str") [return-value]


    def return_annotated_type(context: str = "") -> Any:
    # no error here, but i don't like that Any is too broad.

    Continue reading...

Compartilhe esta Página