Giter Club home page Giter Club logo

Comments (13)

sobolevn avatar sobolevn commented on August 20, 2024 2

Now it is result.alt(raise_exception).unwrap()

from returns.

thedrow avatar thedrow commented on August 20, 2024 1

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.

sobolevn avatar sobolevn commented on August 20, 2024 1

@thedrow I like unwrap_or_raise()!

from returns.

sobolevn avatar sobolevn commented on August 20, 2024

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.

sobolevn avatar sobolevn commented on August 20, 2024

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.

sobolevn avatar sobolevn commented on August 20, 2024

Closed via #57

from returns.

thedrow avatar thedrow commented on August 20, 2024

Actually this isn't resolved since you still can't catch the original exception.

from returns.

thedrow avatar thedrow commented on August 20, 2024

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.

sobolevn avatar sobolevn commented on August 20, 2024

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.

sobolevn avatar sobolevn commented on August 20, 2024

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.

thedrow avatar thedrow commented on August 20, 2024

I really don't mind having rich APIs as long as they are properly documented and tested.

from returns.

sobolevn avatar sobolevn commented on August 20, 2024

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.

sobolevn avatar sobolevn commented on August 20, 2024

Closed by 4e9ab7b

from returns.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.