Comments (13)
Now it is result.alt(raise_exception).unwrap()
from returns.
I'd like to use try-except because it's the only effective, clear and idiomatic way to handle different types of errors.
Your suggestion seems to involve checking if the Result
is a Failure
:
if not is_successful(result):
try:
result.failure()
except Whatever:
pass
Which is also a dance I'd like to avoid.
I tried using a metaclass in order to pretend to be another exception but that doesn't work unfortunately.
class ExcMeta(type):
def __instancecheck__(cls, i):
print(cls)
print(i)
return True
def __subclasscheck__(cls, i):
print(cls)
print(i)
return True
class Exc(Exception, metaclass=ExcMeta):
pass
e = Exc("OMG")
try:
raise e
except ValueError:
print("Handled")
except Exc:
print("Boo")
This program prints Boo.
If we can fool the exception matching mechanism to catch both the inner exception and the UnwrapFailedError
that we'll have something we can use.
from returns.
@thedrow I like unwrap_or_raise()
!
from returns.
Hi, @thedrow! Thanks for your feedback.
But, I do not understand what exactly you are trying to achieve.
Let's say I unwrap a failure and want to catch it using try-except
But why do you want to do it? In case you need an exception you can do it like so:
container: Failure[SomeException]
exc = container.failure()
But, I would like to remove UnwrapFailedError
if you can provide a sample on how it is possible without internal exceptions.
from returns.
Will this sample work for you?
from typing import NoReturn
from returns.result import Failure
def raise_(exception: Exception) -> NoReturn:
raise exception
try:
# Setting up imaginary instance:
result = Failure(TypeError('my message'))
# Raising actual exception:
result.fix(raise_)
except ValueError as ex:
print('value:', ex)
except TypeError as ex:
print('type:', ex)
except Exception as ex:
print('base:', ex)
# => type: my message
If so, we can make raise_
function a part of our functions.py
file.
from returns.
Closed via #57
from returns.
Actually this isn't resolved since you still can't catch the original exception.
from returns.
It does provide more information and you can now do the following:
try:
result.unwrap()
except UnwrapFailedError as e:
if isinstance(e.__cause__, ValueError):
print('ValueError %s' % e)
This is better but still isn't the desired result.
What about adding an unwrap_or_raise()
method which either unwraps the value or raises the original exception?
from returns.
So, @thedrow, if I understand you correctly we have to support the following case:
result: Failure[ValueError]
result.unwrap() # => fails with UnwrapFailedError(ValueError(...))
We need to actually raise the inner exception:
# returns/functions.py
def raise_exception(exception: Exception) -> NoReturn:
raise exception
# sample_code.py
from returns.functions import raise_exception
result: Failure[ValueError]
result.fix(raise_exception) # => ValueError(...)
other_result: Failure[IndexError]
other_result.unwrap_or_raise() # => IndexError(...)
What do you think about two ways of raising exceptions? Can we just stick to fix(raise_exception)
?
Do we really need unwrap_or_raise()
?
I am opened to the suggestions.
from returns.
inb4: I am not a big fan of rich API, since at some point it will look something like this: https://github.com/gcanti/fp-ts/blob/master/docs/modules/TaskEither.ts.md#taskeither-class
from returns.
I really don't mind having rich APIs as long as they are properly documented and tested.
from returns.
Ok, so here's my proposal: the goal of this library is to use monads, not exceptions in the first place.
It should be really strange to add unwrap_or_raise()
since it contradicts with the initial intention.
As a result, we will stick to the raise_exception
helper function and fix()
. Here' how you can unwrap values the true way:
result: Result[int, ZeroDivisionError]
# This only makes sense if you need this exception in your third-party API:
result.fix(raise_exception).unwrap()
from returns.
Closed by 4e9ab7b
from returns.
Related Issues (20)
- Changes `impure_safe` to have the same arguments as `safe` decorator
- error: Error importing plugin "returns.contrib.mypy.returns_plugin": No module named 'returns' [misc] HOT 7
- Use with Sentry HOT 2
- Please help installing returns with pyproject.toml HOT 3
- Do Notation not accepting variable from previous statement HOT 1
- How to run an example under asyncio? HOT 1
- Question. Async SQLAlchemy from sync methods HOT 2
- Consider vendoring `curio` HOT 1
- Feature Request: Convenience constructor for Result HOT 2
- Feature Request: convenience method for ResultE.unwrap() HOT 2
- mypy error for HKT example from docs HOT 5
- Breaking deserialization backward compatibility between 0.19.0 and 0.20.0 HOT 1
- Hypothesis plugin need an update
- Update mypy
- Feature Request: Let Pipe function take more than 1 positional argument. HOT 1
- Document methods.cond vs pointfree.cond HOT 3
- Mypy 1.6.1 fails with returns 0.21.0 on use of `curry.partial` HOT 5
- How to declare type of new variables in Success and Failure instantiations for MyPy HOT 5
- "Nitpick" in documents goes to a dead link
- Help needed: error handling HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from returns.