Returning from a multiple stacked call at once

Avi Gross avigross at verizon.net
Sat Dec 12 13:21:02 EST 2020


As always, it may be useful to know WHY the questioner wants to skip
intermediate functions already in progress and jump back to some unspecified
earlier level.

There is a reason why functions are "stacked" and there are data structures
that really may need to be unwound. But if the question is not about some
sort of "efficiency" or speed but about ways to write the code so once
something has been found, it can fairly directly return, that does have
answers.

Tail recursion is an example, sometimes real as in the function is overlaid
and there is no need to return and sometimes sort of simulated with overhead
remaining but it looks like it returned. 

If all the functions written are your own, then simply calling your next
function that you want to be the return value (from anywhere applicable in
the function, not just the end, is easy enough to write as:

	return(next_function(args))

It will still unwind but logically will act as if it just returns without
the need for the functions to be written with lots of if statements or
twisted logic so nothing much gets done after the right result is obtained. 

And, of course, there are exceptions. If you raise an exception that you
know will not be caught until you reach the level where you do catch it, you
can sort of sail through any of the functions between and bypass any logic
that might otherwise be there for a normal return.

Arguably it might be better to write your code carefully so upon success, it
unwinds easily and only in low probability cases look for an abrupt exit.

And for a really abrupt exit, there is a way to shut down the program very
abruptly perhaps even too abruptly.

-----Original Message-----
From: Python-list <python-list-bounces+avigross=verizon.net at python.org> On
Behalf Of Dieter Maurer
Sent: Saturday, December 12, 2020 12:20 PM
To: ast <ast at invalid>
Cc: python-list at python.org
Subject: Re: Returning from a multiple stacked call at once

ast wrote at 2020-12-12 07:39 +0100:
>In case a function recursively calls itself many times, is there a way 
>to return a data immediately without unstacking all functions ?

Python does not have "long jump"s (out of many functions, many loop
incarnations).
In some cases, you can use exceptions to emulate "long jump"s.
--
https://mail.python.org/mailman/listinfo/python-list


Scanned by McAfee and confirmed virus-free.	
Find out more here: https://bit.ly/2zCJMrO



More information about the Python-list mailing list