Consider the recursive implementation of factorial function -
from typing import Optional
def factorial(val: int) -> Optional[int]:
if val<0:
return None
if val==0:
return 1
return val*factorial(val-1)
if __name__ == "__main__":
print(square_root(3))
I am using mypy for static type checking. It throws me the following error -
type-hints.py:8: error: Unsupported operand types for * ("int" and "None")
type-hints.py:8: note: Right operand is of type "Optional[int]"
Found 1 error in 1 file (checked 1 source file)
I tried using Optional as per this stackoverflow question. But it doesn't seem to work. Any suggestions?
Questions -
- How to specify return type when the function returns
None? - Seems a bit surprising to me that mypy was able to envision a situation where multiplication between
intandNonemight occur. For example - If I removeintfor val argument and call the factorial function with a float, it might throw such error.