How to wrap a class's methods?

Steven Bethard steven.bethard at gmail.com
Thu Feb 17 15:09:42 EST 2005


Grant Edwards wrote:
> I want to subclass an IMAP connection so that most of the
> methods raise an exception if the returned status isn't 'OK'.
> This works, but there's got to be a way to do it that doesn't
> involve so much duplication:
> 
> class MyImap4_ssl(imaplib.IMAP4_SSL):
> 
>     def login(*args):
>         s,r = imaplib.IMAP4_SSL.login(*args)
>         if s!='OK':
>             raise NotOK((s,r))
>         return r
>         
>     def list(*args):
>         s,r = imaplib.IMAP4_SSL.list(*args)
>         if s!='OK':
>             raise NotOK((s,r))
>         return r
>         
>     def search(*args):
>         s,r = imaplib.IMAP4_SSL.search(*args)
>         if s!='OK':
>             raise NotOK((s,r))
>         return r
>         
>     [and so on for another dozen methods]

A more tested version of my other email:

py> class C(object):
...     def f(self, *args):
...         print "f:", args
...     def g(self, *args):
...         print "g:", args
...
py> class D(C):
...     pass
...
py> class Wrapper(object):
...     def __init__(self, func):
...         self.func = func
...     def __call__(self, *args):
...         print "wrapped"
...         return self.func(*args)
...
py> for name in ['f', 'g']:
...     wrapper = Wrapper(getattr(C, name))
...     setattr(D, name, new.instancemethod(wrapper, None, D))
...
py> C().f()
f: ()
py> C().g(1)
g: (1,)
py> D().f()
wrapped
f: ()
py> D().g(1)
wrapped
g: (1,)



More information about the Python-list mailing list