0

Is there any way for mypy to support instance checking from within a function?

I am aware of the isinstance support for complex type checking. I have the following module as minimal example for illustration purposes:

from typing import Any, Union

def is_str(argument: Any) -> bool:
    return True if isinstance(argument, str) else False

def my_string_function(input_str: str):
    print(input_str)

def my_string_and_int_function(argument: Union[str, int]):

    if is_str(argument):
        my_string_function(argument)

    if isinstance(argument, str):
        my_string_function(argument)

Now if I run mypy I get the following error for the first (not the second!) function call of my_string_function from within the my_string_and_int_function:

error: Argument 1 to "my_string_function" has incompatible type "Union[str, int]"; expected "str"

Maybe this is more appropriate for the mypy issue tracker but as I am unsure I thought of posting it here first.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
sh0rtcircuit
  • 445
  • 3
  • 13

0 Answers0