Structural pattern matching not matching stored failure value
ogabrielsantos opened this issue · 4 comments
Bug report
What's wrong
I'm trying to match some exceptions using structural pattern matching after reading the documentation, which says that I can match by result stored inside Failure
(here):
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):
# [...] omitted
# Matches if the result stored inside `Failure` is `ZeroDivisionError`
case Failure(ZeroDivisionError):
print('"ZeroDivisionError" was raised')
# [...] omitted
So, I've tried to implement my own code and looks like the first defined failure will be called, independent of it's value. Lets try it:
from returns.result import Failure, Success, Result
def foo(x) -> Result[float, str]:
return Failure("Some dumb error")
match foo(10):
case Failure(ZeroDivisionError):
print("matched ZeroDivisionError failure")
case Failure(str):
print("matched string failure")
case _:
print("no failure matched")
# prints: matched ZeroDivisionError failure
How is that should be
Assuming above code, it should've printed matched string failure
System information
python
version: 3.10.5 (main, Jun 23 2022, 17:14:57) [Clang 13.1.6 (clang-1316.0.21.2.5)]returns
version: 0.19.0mypy
version: 0.961hypothesis
version (if any): absentpytest
version (if any): 6.2.5
I'll take a look to see why this is happening!!
Ok, I just found the problem and it's in our documentation 😆
To match correctly use parenthesis, Failure(ZeroDivisionError())
! Could you test again using parenthesis @ogabrielsantos, please?
I knew that I've tested a case with exceptions inside a Failure
container:
https://github.com/dry-python/returns/blob/master/tests/test_pattern_matching.py
cc @sobolevn
@thepabloaguilar I've solved this issue yesterday reading the above mentioned test but had no time to get here and report it because I was out of office. Thanks!
For the documentation issue, how about a more non-generic example, showing the advantage/usage of Result
for multiple Failure
types?
What do you have in mind? Feel free to submit a PR to us, help is always welcome!!