How can one create a function that narrows the type of a variable (for static type checkers) in a similar way to isinstance?
For example, ComplexTypeAssertion just narrows the type at runtime but not for static checks:
def MyFunction(myData: object) -> object:
if isinstance(myData, list):
reveal_type(myData) # Revealed type is 'builtins.list[Any]'
if ComplexTypeAssertion(myData): # <<< How to make MyPy understand this?
reveal_type(myData) # Revealed type is 'builtins.object'
def ComplexTypeAssertion(data: object) -> bool:
return isinstance(data, list) and all(isinstance(value, str) for value in data)
How could I define ComplexTypeAssertion such that static analysis tools would understand the type?
Obviously, this is a toy example, real life examples would be more complex. It would be very useful in situations where I want to assert that some data follows a TypedDict construct or other typing constructs.