by N1H1L · 1y ago · 0 comments
from typing import Optional, Union
def square(
a: Union[int, float],
b: Optional[int] = 2
) -> float:
c = a**b
return c
Many type checkers throw an error because `Optional[int]` actually means `int | None` and you cannot square an `int` or a `float` with a `None`. Is there any plans for *ty* around this?To handle this you would need to use "narrowing" to separately handle the case where `b` is `None`, and the case where it is not:
def square(a: Union[int, float], b: Optional[int] = 2) -> float:
if b is None:
return 0
else:
c = a**b
return c
https://play.ty.dev/97fe4a09-d988-4cc3-9937-8822e292f8d1(This is not specific to ty, that narrowing check should work in most Python type checkers.)