Invoking return through a function?

bartc bc at freeuk.com
Sun Oct 29 11:13:22 EDT 2017


On 29/10/2017 14:35, Steve D'Aprano wrote:
> On Mon, 30 Oct 2017 01:18 am, Alberto Riva wrote:

>> I'm wondering if there is a way of writing a function that causes a
>> return from the function that called it.

> You really should re-think your strategy. Your suggestion, if possible, would
> lead to difficult to maintain code where you couldn't easily tell where the
> exit points of a function where. Imagine reading code like:
> 
> 
> def foo(x):
>      a = sin(x)
>      b = cos(x)
>      print(a, b)
>      return a + b
> 
> There's one return, right? No. If Python could do what you are asking for,
> *every function call* could be a hidden, secret return. What a nightmare that
> would be.
> 
> It is bad enough that any function could raise an exception,

Don't exceptions do exactly the same thing as what the OP is proposing? 
Worse, actually.

That is, it could stop executing during any of the first three lines of 
foo(), and end up continuing execution in the caller, or in the caller's 
caller, and so on.

> but at least
> exceptions halt the normal execution of code (unless explicitly caught). They
> don't silently continue normal execution.

I'm having trouble seeing the difference. If F calls G calls H, then H 
can arrange an exception to be picked up by F, bypassing normal return 
paths back to G and back to F.

And there's nothing G can do about it. At least, not without a lot of 
trouble, like wrapping try/except around every statement and 
sub-statement in G.

(What the OP wants was also proposed a few weeks back in comp.lang.c. 
But that was only within nested functions, so if H is inside G, and G is 
inside F, then a 'returnall' from H would return directly directly from 
F. Apparently Lisp allows this...)

-- 
Bartc



More information about the Python-list mailing list