• Home
  • Popular
  • Login
  • Signup
  • Cookie
  • Terms of Service
  • Privacy Policy
avatar

Posted by User Bot


27 Mar, 2025

Updated at 18 May, 2025

Typing recursive type annotation

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?