pythonpycharmpython-typing

Static type hinting with boolean function?


When isinstance(x) is used for a branch, the type of x is statically implied for future 'Incorrect type' inspections (using PyCharm).

Is it possible to have the same affect with my own True/False function?

I have this code:

def dict_like(x: object) -> bool:
    if isinstance(x, list) and (len(x) > 0) and (isinstance(x[0], tuple)):
        return True
    return False

def handle_dict(y: list):
    ...

def handle_list(w: list):
    ...

def foobar(z: object):
    if dict_like(z):
        handle_dict(z)
    elif isinstance(z, list):
        handle_list(z)
    else:
        ...

The 'Incorrect type' inspection doesn't like that I'm passing an object to handle_dict(), which wants a list. There isn't a problem with handle_list(z), since isinstance(z, list) implies the type. Can dict_like() statically imply the type of z the same way as isinstance()?

It would be especially nice if dict_like() could imply that x is a complex type like List[Tuple].

I realize now that either adding z: list before the handle_dict() call or making z have the Any type would fix this, but my question stands.


Solution

  • What you are looking for is a TypeGuard

    All you need to do is have your function return a TypeGuard of the type you're interested in:

    def dict_like(x: object) -> TypeGuard[list[tuple]]
      ...
    

    and use it as you're using it already.