On 10/29/2017 10:35 AM, Steve D'Aprano wrote:
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.

That's just because I used a name that was too generic in my example. I can call it "returnIfKeyMissing", and then it would be clear.

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.

But again, it's just a naming problem. Something like returnIfKeyMissing would make it easy to tell where the exit points are. And as Bartc pointed out, we already have this situation with exceptions, so it would be nothing new. Indeed, what I'm asking for could be accomplished by wrapping the body of each function in a try/catch block for an ad-hoc exception type. But again, since the language doesn't have macros, this would have to be done manually in each function. I was just asking for a more convenient way to do it, being a lazy programmer :)

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.

See above :)

Thanks,

Alberto


--
                E-mail address:
((lambda (s a b c) (map 'string #'code-char (mapcar (lambda (v)
(setq s (+ a (mod (+ s v (- a)) b)))) (map 'list (lambda (v)
(- (char-code v) c)) " 1`-THUZ&+Wh1")))) 97 46 73 32)
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to