Two python method are defined as:
def function() -> Optional[ast.Module]:
pass
def something(t: ast.Module) -> None:
pass
In a caller:
var = function()
if var:
do_something(var)
The type-checker complains that I can't pass an Optional[t] to t. I imagine that there's some sort of casting mechanism, but it escapes me.
To be precise, this is a unit test and looks like:
self.assertIsNotNone(var)
do_something(var)
With respect to possible duplicate Optional type annotation. Using value after checking if is None?,
new_var: ast.Module = var
gets the same type error.
Is an 'if' required?
One has to explicitly exclude the case that the value is identical to None, not just any false’y value.
var: Optional[...] = function()
if var is not None: # reject None case in this branch
do_something(var) # `var` is the unwrapped type
The inverse is also possible:
var: Optional[...] = function()
if var is None: # handle None case in this branch
...
else: # no more None case in this branch
do_something(var) # `var` is the unwrapped type
Note that type checkers cannot inspect arbitrary functions for type guards. An implicit rejection such as self.assertIsNotNone(var) is not equivalent to an explicit check against None. An additional, explicit exclusion is required.
self.assertIsNotNone(var)
assert var is not None # reject None case after this point
do_something(var)
Of course, it is always possible to cast away the option. Since this disables verification for the variable type, it should generally only be a last resort.
do_something(cast(ast.Module, var))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With