dry-python/returns

How to declare type of new variables in Success and Failure instantiations for MyPy

Closed this issue · 5 comments

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.

sorry, the example you provided is not enough.
what is function()?

it's a method with @safe decorator

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(_):

Sorry, I cannot reproduce.
Снимок экрана 2024-01-08 в 14 33 11

Do you use the latest version?

Thanks ! I found the reason: It's due to follow_imports = "skip" in pyproject.toml though we have plugins = ["returns.contrib.mypy.returns_plugin"]...