I'm used to typescript, in which one can use a !
to tell the type-checker to assume a value won't be null. Is there something analogous when using type annotations in python?
A (contrived) example:
When executing the expression m.maybe_num + 3
in the code below, the enclosing if
guarantees that maybe_num
won't be None
. But the type-checker doesn't know that, and returns an error. (Verified in https://mypy-play.net/?mypy=latest&python=3.10.) How can I tell the type-checker that I know better?
from typing import Optional
class MyClass:
def __init__(self, maybe_num: Optional[int]):
self.maybe_num = maybe_num
def has_a_num(self) -> bool:
return self.maybe_num is not None
def three_more(self) -> Optional[int]:
if self.has_a_num:
# mypy error: Unsupported operand types for + ("None" and "int")
return self.maybe_num + 3
else:
return None