Invoking return through a function?
Ned Batchelder
ned at nedbatchelder.com
Sun Oct 29 10:30:19 EDT 2017
On 10/29/17 10: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)
> ...
>
> 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?
>
> 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, there isn't.
--Ned.
More information about the Python-list
mailing list