4 ms·
I have a problem with Python's `Optional` type. For example for this following code: from typing import Optional, Union def square( a: Union[int, f
by N1H1L 1y ago
I have a problem with Python's `Optional` type. For example for this following code:
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?
- dcreager 1y agoI think that's a genuine error, since as you say, `None` is a possible value for `b` according to your signature. 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 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.)