On 2020-05-02 11:59 a.m., Eric V. Smith wrote:
On 5/2/2020 7:18 AM, Alex Hall wrote:
On Sat, May 2, 2020 at 12:39 PM Henk-Jaap Wagenaar <wagenaarhenkj...@gmail.com <mailto:wagenaarhenkj...@gmail.com>> wrote:

    Of course, there are other ways of writing this code, but imagine
    this for a database interface where a save normally returns the
    saved object (inspired by Django)

    ```
    try:
        x, y = Foo.save()
    except ValueUnpackingError:
        // oh... this means saving failed (it returned None instead)
        // let's return a sensible response
        return ExceptionToResponse(FooStateToException(foo.state))
    ```


My concern is that this is risky code. If `Foo.save()` has a bug somewhere inside (or maybe it calls back to your own code which has a bug) it could raise `ValueUnpackingError` for different reasons, and then that gets caught and misleads people into thinking that Foo.save returned None which leads to all sorts of frustration and confusion.

This code:

```
result = Foo.save()
if result is None:
    return ExceptionToResponse(...)
x, y = result
```

is not sexy, but it's explicit, safe, and it targets the real problem precisely.

Creating these new exceptions would encourage people to write code that will bite them later.

I agree that we don't want to encourage code like the above example with catching the hypothetical ValueUnpackingError. I contend that even if we added ValueUnpackingError, no one would ever write code that used it, but should instead do what they do now: unpack it after checking it (as Alex's example shows). Of course, that's a horrible API, but sometimes you have to call horrible APIs. The fact that the API is bad doesn't mean we should add a way to handle it poorly.

The only reason I'd want it to exist (and I don't) is to see it in the REPL. But for that, there's the exception message and the traceback, so a unique exception for this would be useless to me.


how about:

result = Foo.save()
try:
  x, y = result
except ValueUnpackingError:
  return ...

this would also handle generators (and, the unpacking operation should wrap the generator's ValueUnpackingError (if any) in a RuntimeError so it doesn't conflict with the unpacking operation's API)
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/DSCJVOQYV4NJR6AOHSTJJ4DUOVKESUZ4/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to