Revisiting variance

The code sample referenced above (the is_seq_b function) strikes me as a buggy implementation of a type guard function.

It’s trivial to create examples of type guard functions that misuse TypeIs (or TypeGuard). These will produce no type errors and mask actual bugs in your code. Here’s another example.

Code sample in pyright playground

from typing import TypeIs

def is_int(x: int | str) -> TypeIs[int]:
    # Buggy type guard function
    return True

def func(x: int | str):
    if is_int(x):
        print(x + 1)

func("") # Crash

I don’t think this is a problem with TypeIs, with the handling of variance, or with the type system in general. Not all bugs in your code will be caught by a static type checker. The static type system is a tool that can be used to improve the robustness of your code. You get to decide how to use (or misuse) features of the type system, and your results will vary accordingly.

TypeIs is a relatively advanced typing feature that most Python developers will never be aware of or use directly in their code. For more sophisticated developers who want to make direct use of this feature of the type system, there will always be the potential for misuse.

Perhaps what you’re raising here is the need for improved education. A typing system guide that provides some guidelines for proper use of TypeIs would be welcome if anyone would like to contribute.

3 Likes