How to pop the interpreter's stack?
Ethan Furman
ethan at stoneleaf.us
Mon Dec 27 08:07:16 EST 2010
Steven D'Aprano wrote:
> On Sun, 26 Dec 2010 09:15:32 -0800, Ethan Furman wrote:
>
>> Steven D'Aprano wrote:
>>> Right. But I have thought of a clever trick to get the result KJ was
>>> asking for, with the minimum of boilerplate code. Instead of this:
>>>
>>>
>>> def _pre_spam(args):
>>> if condition(args):
>>> raise SomeException("message")
>>> if another_condition(args):
>>> raise AnotherException("message")
>>> if third_condition(args):
>>> raise ThirdException("message")
>>>
>>> def spam(args):
>>> _pre_spam(args)
>>> do_useful_work()
>>>
>>>
>>> you can return the exceptions instead of raising them (exceptions are
>>> just objects, like everything else!), and then add one small piece of
>>> boilerplate to the spam() function:
>>>
>>>
>>> def _pre_spam(args):
>>> if condition(args):
>>> return SomeException("message")
>>> if another_condition(args):
>>> return AnotherException("message")
>>> if third_condition(args):
>>> return ThirdException("message")
>>>
>>> def spam(args):
>>> exc = _pre_spam(args)
>>> if exc: raise exc
>>> do_useful_work()
>> -1
>>
>> You failed to mention that cleverness is not a prime requisite of the
>> python programmer -- in fact, it's usually frowned upon. The big
>> problem with the above code is you are back to passing errors in-band,
>> pretty much completely defeating the point of have an out-of-band
>> channel.
>
> How is that any worse than making _pre_spam() a validation function that
> returns a bool?
>
> def spam(args):
> flag = _pre_spam(args)
> if flag: raise SomeException()
> do_useful_work()
Also -1.
> Is that also frowned upon for being too clever?
Frowned upon for being out-of-band, and not as much fun as being clever.
;) I'm pretty sure you've expressed similar sentiments in the past
(although my memory could be failing me).
More to the point, the OP had code that said:
args, kwargs = __pre_spam(*args, **kwargs)
and __pre_spam was either passing back verified (and possibly modified)
parameters, or raising an exception.
~Ethan~
More information about the Python-list
mailing list