A class with eventhandlers ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Runsun Pan

    #1

    A class with eventhandlers ?

    Is it possible to code a class that raise exception
    automatically when an error occurs?

    We usually use try-except pair at where we expect an
    error might occur. What am thinking is a class that
    has built in error handling so we can do this:

    c=MyClass()
    c.onError = some_hook

    or

    c.onError('Inde xError', IndexErrorHook)

    or, more specific, a function/method-specific error
    handling feature:

    c.load.onError( IOErrorHook)
    c.load( filename )

    Is there such a mechnism around? If not, is it possible
    to make such a thing ?

    --
    ~*~*~*~*~*~*~*~ *~*~*~*~*~*~*~* ~*~*~
    Runsun Pan, PhD
    python.pan@gmai l.com
    Nat'l Center for Macromolecular Imaging

    ~*~*~*~*~*~*~*~ *~*~*~*~*~*~*~* ~*~*~
  • Alex Martelli

    #2
    Re: A class with eventhandlers ?

    Runsun Pan <python.pan@gma il.com> wrote:
    ...[color=blue]
    > or, more specific, a function/method-specific error
    > handling feature:
    >
    > c.load.onError( IOErrorHook)
    > c.load( filename )
    >
    > Is there such a mechnism around? If not, is it possible
    > to make such a thing ?[/color]

    Never heard of one, but you could surely make a custom metaclass
    satisfying your specs (==wrapping each method into an instance of a type
    providing such an onError method, as well as a __call__ delegating to
    the real method within a suitable try/except). Sounds like a lot of
    work to me, though;-).


    Alex

    Comment

    • Farshid Lashkari

      #3
      Re: A class with eventhandlers ?

      It's definitely possible, here's a small example. There are probably
      better ways to do it, but I'll let you figure that out ;)

      class ErrorHandler:
      def __init__(self,m ethod):
      self.method = method
      self.errorHook = None

      def onError(self,ho ok):
      self.errorHook = hook

      def __call__(self, *args, **kwargs):
      if self.errorHook:
      try:
      self.method(*ar gs,**kwargs)
      except Exception, e:
      self.errorHook( e)
      else:
      self.method(*ar gs,**kwargs)


      class MyClass:
      def __init__(self):
      self.load = ErrorHandler(se lf.load)

      def load(self,filen ame):
      return self.x

      def IOErrorHook(e):
      print 'Caught error:',e

      c = MyClass()
      c.load.onError( IOErrorHook)
      c.load('filenam e')

      Comment

      Working...