Title: Allow return mismatch to be caught by function
Type: enhancement Stage: resolved
Components: Interpreter Core Versions: Python 3.5
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: Ted Shaneyfelt, eric.smith
Priority: normal Keywords:

Created on 2017-02-06 21:11 by Ted Shaneyfelt, last changed 2017-02-07 00:55 by eric.smith. This issue is now closed.

Messages (2)
msg287173 - (view) Author: Ted Shaneyfelt (Ted Shaneyfelt) Date: 2017-02-06 21:11
def f():
    try: return 0
    except: return 1,2

x = f() # x is 0
x,y = f() # proposal: x,y should be 1,2 instead of uncaught TypeError

It would make sense to be able to catch [TypeError: 'int' object is not iterable] and return the correct number of values. Yes, the way it's done now, the function is no longer running when it is caught - but is it possible and practical to determine if parameters match before the function returns instead of afterward, allowing the called function to catch the error attempting to return?
msg287182 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2017-02-07 00:55
Thanks for the suggestion. However, I don't think it's possible or desirable for python to implement this.

There are two problems: 1) the internals of python would have to be drastically changed to support this, and 2) you'd need different syntax to support this.

For item 2, consider:

def f():
    try: return some_other_function()
    except: return 1,2

You can't distinguish between your proposed type mis-match exception and some_other_function() raising a TypeError. I suppose you could invent another exception type, but you'll always have a similar problem.

A larger problem is that this behavior would be confusing to both newcomers and existing programmers, it adds nothing that can't currently be done, and it would be a source of subtle bugs.

If you really want to explore this, I suggest working out a more complete example and bringing it up on the python-ideas mailing list.

You'll want to include code that currently exists that would be made simpler with your proposal. If you can find any such code in the standard library, that would be a bonus.

Thanks again.
Date User Action Args
2017-02-07 00:55:03eric.smithsetstatus: open -> closed

nosy: + eric.smith
messages: + msg287182

resolution: rejected
stage: resolved
2017-02-06 21:11:31Ted Shaneyfeltcreate