Invoking return through a function?

Steve D'Aprano steve+python at pearwood.info
Sun Oct 29 10:35:33 EDT 2017


On Mon, 30 Oct 2017 01:18 am, Alberto Riva wrote:

> Hello,
> 
> I'm wondering if there is a way of writing a function that causes a
> return from the function that called it. To explain with an example,
> let's say that I want to exit my function if a dict does not contain a
> given key. I could write:
> 
> def testFun():
>    ...
>    if key not in dict:
>      return
>    ...
> 
> But if this is a test I need to do a lot of times, I'd like to replace
> it with something shorter and more explicit:
>
> def testFun():
>    ...
>    checkKey(dict, key)
>    ...

You mean *less* explicit. "checkKey" gives absolutely no hint that it causes
the current function to return.


> and I'd like checkKey to cause a return *from testFun*. In a language
> like Lisp this would be accomplished by defining checkKey as a macro
> that expands into the code shown in my first example, so that the return
> would be inside testFun and not insted checkKey. Is there a way of doing
> something like this in Python?

Fortunately not.


> Another way of phrasing my question is: is there a way to cause a return
> from a function that is higher up in the call stack, rather than the
> currently active one, without using try/except?

No.

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, but at least
exceptions halt the normal execution of code (unless explicitly caught). They
don't silently continue normal execution.


-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list