method for Exception base class to raise the exception in an expression?

Discussion in 'Python' started by Bengt Richter, Jul 7, 2005.

  1. 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
    Bengt Richter, Jul 7, 2005
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jacol

    raise or not to raise [Newbie]

    Jacol, Feb 3, 2007, in forum: Python
    Replies:
    5
    Views:
    396
    Gabriel Genellina
    Feb 5, 2007
  2. ernest
    Replies:
    2
    Views:
    273
    Roy Smith
    Nov 14, 2010
  3. Jack Bates
    Replies:
    0
    Views:
    265
    Jack Bates
    May 2, 2011
  4. Karan Rajput
    Replies:
    2
    Views:
    130
    Abinoam Jr.
    Dec 22, 2010
  5. bvdp

    Raise X or Raise X()?

    bvdp, Mar 11, 2012, in forum: Python
    Replies:
    10
    Views:
    346
    Stefan Behnel
    Mar 12, 2012
Loading...

Share This Page