On Thu, Feb 21, 2019 at 07:05:55PM +1100, Chris Angelico wrote: [Ben] > > Other functions also conceptually have three ways of returning: > > ordinary return with a value, a documented special return like > > KeyError, and pass-through exceptions. If the pass-through exception > > is KeyError, it gets conflated with the documented exceptional return, > > but correct code should handle them differently. It doesn't matter > > whether the syntax for the documented special return is "return x" or > > "raise KeyError(x)". > > Not sure what you mean here. If the documented special return is > "return x", then it's a value that's being returned. That's completely > different from raising some sort of exception.
I think I understand what Ben means, because I think I've experimented with functions which do what he may be getting at. Remember that exceptions are not necessarily errors. So you might write a function which returns a value in the standard case, but raises an exception to represent an exceptional case. If this is not an error, then the caller ought to be prepared for the exception and always catch it. This could be considered an alternative design to returning a tuple: (True, value) # standard case (False,) # or raise an exception If this seems strange, it actually isn't *that* strange. It is very similar to the way iterators yield a value in the standard case, and raise StopIteration to signal the non-standard, non-erroneous but exception case of having reached the end of the iterator. Another potential example would be searching, where "Not Found" is not necessarily an error, but it is always an exceptional case. The built-ins raise KeyError or ValueError (for str.index) but they could have just as easily raise KeyNotFound and SubstringNotFound. So exceptions do not necessarily represent errors that should bubble up to the user, to be reported as a bug. They can also represent an alternative (if slightly clumsy) mechanism for passing information to the caller. -- Steven _______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/