[Python] Typing recursive type annotation

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

  1. Stack

    Stack Membro Participativo

    I have a function which takes a value, a type annotation, and validates that the value is of the type.

    It only takes a certain subset of type annotations: int, float, str, bool, a list of any of these, or a (potentially nested) list of any of these.

    def validate(value: Any, type_: ValidatableAnnotation):
    ...


    I have no problem implementing the function, however, I have a problem typing it.

    I'm trying to define the type ValidatableAnnotation to allow any level of recursion in the list type e.g. list[int], list[list[int]] etc. ad infinitum.

    My best attempt:

    ValidatableAnnotation = (
    Type[str] | Type[int] | Type[float] | Type[bool] | Type[list["ValidatableAnnotation"]]
    )


    However, while it works for the atomic values, it doesn't work for lists:

    validate([1], list[int]) # Incompatible types in assignment (expression has type "type[list[int]]", variable has type "ValidatableAnnotation")


    Is the Python (3.10) type system capable of doing what I want here, and if so how do I do it?

    Edit: similarity has been pointed out to What's the correct type hint for a type hint?. However, it is possible that an answer is available at a lower level of generality than at a higher level. I'm not asking for a general answer to "how to define a type hint for a type hint", but for a specific answer to "how to recursively define a type hint for a list type hint. This specific scenario may have a solution even if the more general question doesn't.

    Continue reading...

Compartilhe esta Página