How to declare type of new variables in Success and Failure instantiations for MyPy
Closed this issue · 5 comments
christopher5106 commented
I was wondering how to declare the type of variables response and error for MyPy:
match function():
case Success(response): # type: ignore[misc]
.....response...
case Failure(error): # type: ignore[misc]
raise error
Currently, I had to add # type: ignore[misc]
which disables lot's of validation in the block by Mypy, which is bad.
sobolevn commented
sorry, the example you provided is not enough.
what is function()
?
christopher5106 commented
it's a method with @safe
decorator
christopher5106 commented
we can take the method from the docs also:
from returns.result import Failure, Success, safe
@safe
def div(first_number: int, second_number: int) -> int:
return first_number // second_number
match div(1, 0):
# Matches if the result stored inside `Success` is `10`
case Success(10):
print('Result is "10"')
# Matches any `Success` instance and binds its value to the `value` variable
case Success(value):
print('Result is "{0}"'.format(value))
# Matches if the result stored inside `Failure` is `ZeroDivisionError`
case Failure(ZeroDivisionError()):
print('"ZeroDivisionError" was raised')
# Matches any `Failure` instance
case Failure(_):
print('The division was a failure')
Mypy says:
tests.py:11: error: Expected type in class pattern; found "Any" [misc]
tests.py:15: error: Expected type in class pattern; found "Any" [misc]
tests.py:19: error: Expected type in class pattern; found "Any" [misc]
tests.py:23: error: Expected type in class pattern; found "Any" [misc]
Found 4 errors in 1 file (checked 1 source file)
The lines raising the mypy error:
case Success(10):
case Success(value):
case Failure(ZeroDivisionError()):
case Failure(_):
sobolevn commented
christopher5106 commented
Thanks ! I found the reason: It's due to follow_imports = "skip"
in pyproject.toml though we have plugins = ["returns.contrib.mypy.returns_plugin"]
...