this post was submitted on 15 Nov 2023
24 points (87.5% liked)

Python

6496 readers
1 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

πŸ“… Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

🐍 Python project:
πŸ’“ Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 2 years ago
MODERATORS
 

This is a discussion on Python's forums about adding something akin to a throws keyword in python.

you are viewing a single comment's thread
view the rest of the comments
[–] sugar_in_your_tea 3 points 1 year ago* (last edited 1 year ago) (2 children)

I disagree, I'd instead like to move toward handling errors as logic, and keeping exceptions for actually exceptional cases. If you're expecting an exception, that's data.

So here's my proposal:

  • introduce monads like Maybe/Result that forces the dev to handle expected errors in logic
  • make an easy way to return errors early without interrupting logic flow
  • simplify checking for None values in chaining

For the first (not exactly a monad, may need a new type to wrap things):

def maybe_err(val: int) -> Result[int, ValueError]:
    if val < 0:
        return ValueError("cannot be negative")
    return val

match (val := maybe_err(-1)):
    case int():
    case ValueError():

For the second:

val = maybe_error(-1)?  # special handling to return instances of Error early

And the third:

val = x?.y?.z ?? DEFAULT

I like this much better than having try/except blocks throughout the code, and reserve those only for logging and whatnot at the top level. If you document exceptions, people will use them even more as data instead of exceptions.

So only raise if you want it to bubble all the way up, return errors if it's just data for the caller. Libraries should almost never raise.

[–] Gallardo994 1 points 1 year ago (1 children)

Anything but over9000 variations of nullables like in C#

[–] sugar_in_your_tea 1 points 1 year ago* (last edited 1 year ago)

I'm not too familiar with C# (last used it like a decade ago), but I think the rules here would be pretty simple:

  • x? - if x is None or an Error, return from the function early, otherwise use the value and continue
  • x?.y - same as above, but with an attribute of x
  • x ?? y - instead of returning as in the first, use y as the default value

And maybe add an option to convert exceptions from a function to an Error value (maybe some_func?() to convert to error values? IDK, I haven't thought through that part as much).

Hopefully that's simple enough to be useful.

If I were proposing this, I'd limit it to optional chaining since that's far more annoying to me currently.