there are a lot of functions and methods that raise exceptions or return value, if we want to suppress the exceptions we shouldn’t need a whole context manager.
and if we are going to use this approach we shouldn’t discard the error or result.
How woudl you use the proposed syntax? Would you start by first checking if there’s an error, and if so, doing something, and if not, doing something else? Replace your if/else with a try/except and you have proper error handling, done the easy way.
Your proposal doesn’t reduce indentation, though. It eliminates the try…except, but replaces it with the need to extract the result and exception from the return value and then check if there was an exception, which almost certainly requires using an if statement. So you have just as much indentation, and more lines of code…
I suggest you do some research into what makes a successful proposal for a language change (“it would be great to have it in Python” isn’t sufficient ). The “Changing Python” section of the devguide is a good place to start.
Getting a change into the language is a lot of work. Are you willing to invest the effort needed to make it happen? If so, then I’d start by finding some objective evidence that your change will improve the language.
Is this something you actually do? Post some example code where you would in fact do this; there’s almost certainly a tidier way. Remember, exceptions do NOT have to be caught the moment that you are aware they could happen! The entire point of exception handling is that, if you can’t handle the exception, don’t.
I cannot think of any situations where I want to (a) do something that might fail, (b) carry on whether or not it failed, and then (c) inspect the failure later on. Usually, if (a) and (b) are true, I can handle the exception immediately (eg having empty data instead of what would have been loaded from a file), even if the true “handling” of the failure is later. I don’t think I’ve ever needed to do tests on the exception itself long after the event.
I might fail this in a code review, depending on the rest of the code. If the API is “return True on Mondays, raise Signal on Tuesdays”, then that’s a problem. If the only way out of the function is an exception, that’s a problem, too.
My point is: whether this is a good pattern depends on the context. There’s not enough info here to make a blanket statement.
I’m not a fan of this proposal, but there is a niche use case. It’s the RPC (Remote Procedure Call) at the low level. The remote side must signalize if it is returning a result or an exception and what is the exact value. The decision how to handle it, is made elsewhere.
Are you actually looking for result-based error handling / result types as a replacement for exceptions? That would be a major paradigm shift for the core language. But there are third-party packages that support this, see e.g. Returns