On Sunday, October 29, 2017 at 9:19:03 AM UTC-5, 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*.
But under what exact _circumstances_? So, you'd like a call to `checkKey(...)` to cause a return in `testFunc` when: (1) the key exists? (2) the key doesn't exist? (3) the dict is actually a list? (3) The call raises an exception? (4) a seg fault occurs? (5) GvR regains his sanity, self-respect and dignity by 86'ing type-hints? Be more specific please. And _always_ refer to a named function by _name_. Never use random or implicit aliases (aka: "the function", "my function", etc...) in your prose. Both functions *ARE* functions, dontchaknow? > In a language like Lisp Python is nothing like Lisp, and for good reason! Sure, we have a few lispers and functional fanboys who hang around here, and sometimes Rustom can get a little preachy about FP, but mostly, we tolerate the fanboyism -- so long as it's not rabid fanboyism. > 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? Thankfully, no. But i wouldn't underestimate the rebellious nature of this generation of Py-dev'ers, and the propensity of these folks to entertain feature creep. > 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? Possibly. But you've already poo-pooed the easy and obvious solution of using conditional logic. -- https://mail.python.org/mailman/listinfo/python-list