I can't seem to find an acceptable annotation for a variable that receives a value that is either: a) function returning int or b) None. The wrinkle is that the function returns a value that is an optional keyword parameter of the parent function, so it was previously declared as Optional[int]. However, the runtime assignment guarantees that the function will never return None.
If I remove the annotation, mypy accepts it as golden. But I'd prefer to use some (acceptable) annotation. In for a penny, in for a pound...
My code:
from typing import Optional, Callable
def myfun(p1: Optional[int] = None):
# mypy complains about this
dyn_p1:Optional[Callable[[], int]] = (lambda: p1) if p1 else None
# ... but has no problem with this
# dyn_p1 = (lambda: p1) if p1 else None
otherFun(dyn_p1)
# I expect the parameter annotation here to be checked at the point of invocation above.
def otherFun(dyn_p1: Optional[Callable[[], int]]):
pass
Here's the mypy error:
PS $ mypy .\prompt_toolkit\shortcuts\test1.py
prompt_toolkit\shortcuts\test1.py:6: error: Incompatible types in assignment (expression has type "Optional[Callable[[], Optional[int]]]", variable has type "Optional[Callable[[], int]]")
prompt_toolkit\shortcuts\test1.py:6: error: Incompatible return value type (got "Optional[int]", expected "int")
Found 2 errors in 1 file (checked 1 source file)
# comment out the first dyn_p1 and uncomment the second, run again:
PS $ mypy .\prompt_toolkit\shortcuts\test1.py
Success: no issues found in 1 source file