[Python] Using Annotated[...] in a type statement

Discussão em 'Python' iniciado por Stack, Outubro 7, 2024.

  1. Stack

    Stack Membro Participativo

    The type statement is relatively new (3.12+) and its support in mypy is experimental:


    PEP 695 type aliases are not yet supported. Use --enable-incomplete-feature=NewGenericSyntax for experimental support
    ​

    Here is a short program were mypy (with the feature enabled) does not like the first two type DataAs.... = ... lines:

    from typing import Annotated
    from pydantic import AfterValidator

    def validate_anything(data):
    return data

    type DataAsDict = Annotated[dict[str, str], AfterValidator[validate_anything]]
    type DataAsList = Annotated[list[str], AfterValidator[validate_anything]]

    type DataType = DataAsDict | DataAsList

    def foo(data: DataType) -> None:
    pass


    The error is (two occurences):


    error: The type "type[AfterValidator]" is not generic and not indexable [misc]
    ​

    Removing the type keyword solves the problem:

    DataAsDict = Annotated[dict[str, str], AfterValidator[validate_anything]]
    DataAsList = Annotated[list[str], AfterValidator[validate_anything]]

    type DataType = DataAsDict | DataAsList


    My relationshiop with typing is experimental too and I'm confused. Has the original code an incorrect typing, i.e. was the mypy right when it detected those errors? Or is the experimental feature not usable for this case yet (that's ok, I was warned).

    Continue reading...

Compartilhe esta Página