Description
I've faced limitation of not narrowing types when trying to add types in https://github.com/openai/gym/blob/8e5ae02ab13a89c976ce7b1278c21f755dfa4bd2/gym/spaces/box.py#L33 - (np.isscalar)[https://numpy.org/doc/stable/reference/generated/numpy.isscalar.html] returning False rules out SupportsFloat
type, and given input type SupportsFloat | np.ndarray
I now know it was narrowed down to np.ndarray.
Numpy has not added type guard yet in its stub, but this is the logical type for this function once all supported python versions will have it. Yet with current syntax it's not possible to describe the function narrowing type by returning False.
Proposal: give TypeGuard second optional argument: TypeGuard[A, B] should narrow argument type A | B to A if returning True, and to B if returning False. Old syntax should still work, where one can have TypeGuard[A] work as it does currently.
I didn't find this in rejected ideas of https://www.python.org/dev/peps/pep-0647/, so wanted to share. I'm not sure how much of stdlib could use this, but it definitely helps to be able to write function in the most semantically convenient way. I can express both "is_x" and "is_not_x" function in typesystem if this is added. This could have synergy with NonType currently being discussed.
Unclear yet: how best to describe situation where no type narrowing occurs on True return, but only on False. Maybe TypeGuard[Any, B]
could have this semantics.