method for Exception base class to raise the exception in an expression?
Bengt Richter
bokr at oz.net
Thu Jul 7 13:07:31 EDT 2005
Sometimes it could be handy, e.g., cutting short iteration:
>>> def raisex(self, *args):
... raise self.__class__(self, *args)
...
>>> Exception.raisex = raisex
>>> list(i for i in xrange(20) if i<10 or StopIteration().raisex())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(i for i in xrange(20) if i<15 or StopIteration().raisex())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> list(i for i in xrange(20) if i<25 or StopIteration().raisex())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
a class method could be nicer once we have Exception as a new-style class.
Just a thought.
Regards,
Bengt Richter
More information about the Python-list
mailing list