Hacker News new | ask | show | jobs
by klyrs 950 days ago
Oh, good, heavyweight error handling just in time for py3.11's zero-cost exception happy path.

But, more generously: why not simply return an error, and use isinstance(val, Error) for error handling? Making objects and calling functions is quite costly, and that can largely be avoided.

3 comments

> Oh, good, heavyweight error handling just in time for py3.11's zero-cost exception happy path.

I don’t get it. Languages that use exceptions for all kinds of errors will also use exceptions for routine errors that happen as a matter of course—the happy path is not the overwhelmingly most common branch, and errors are not exceptional. In turn not zero-cost for all but the exceptional case.

The solution to this is to not use exceptions except for actual errors, unless it's going to be amortized away. For example, objects which have a heavy parameter, which gets memoized. With the zero-cost happy path, you only raise the exception once, when you're doing the costly thing, and subsequent accesses are free.
Sure, it depends on what is expensive. For us, in a primarily asynchronous domain, saving cycles is helpful for lower computational costs and the environment, but in the main, we optimise for reading the code, and one way to lower the cognitive load is to avoid using errors to control flow.
This is what they ended the article on. Return a union type and then error check using isinstance.
Oh, so they did. I guess I got bored after reading so many bad approaches trying to write go/rust in python.