I have a python
script and trying to add type hints to the code, Following is the sample code (without type hints the code works) using mypy
.
values_int: list[int] = [1, 2, 3, 4]
values_str: list[str] = ["1", "2", "3", "4"]
def bar(*, x: list[int]) -> bool:
# processing
return True
def baz(*, y: list[str]) -> bool:
# processing
return True
def foo(*, values: list[int] | list[str]) -> bool:
status: bool = False
if isinstance(values[0], int):
x: list[int] = values
status = bar(x=x)
elif isinstance(values[0], str):
# case-1
# status = baz(y=values)
# case-2
y: list[str] = values
status = baz(y=y)
return status
foo(values=values_str)
Errors for:
# case-1
# error: Argument "y" to "baz" has incompatible type "list[int] | list[str]"; expected "list[str]"
# case-2
# error: Incompatible types in assignment (expression has type "list[int] | list[str]", variable has type "list[str]")