How to wrap a class's methods?

John Lenton john at grulic.org.ar
Thu Feb 17 14:49:11 EST 2005


On Thu, Feb 17, 2005 at 07:32:55PM +0000, 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]
> 

something like this:

    def NotOKVerified(orig):
        def f(*args):
            s, r = orig(*args)
            if s != 'OK':
                raise NotOK((s,r))
            return r
        return f

    class MyImap4_ssl(IMAP4_SSL):
        pass

    for method_name in ('login', 'list', 'search'):
        setattr(MyImap4_ssl, method_name, getattr(IMAP4_SSL, method_name))

?

I'd usually put big fat warnings around this code, and explain exaclty
why I need to do things this way...

-- 
John Lenton (john at grulic.org.ar) -- Random fortune:
"To vacillate or not to vacillate, that is the question ... or is it?"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 196 bytes
Desc: Digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20050217/04be8b7b/attachment.sig>


More information about the Python-list mailing list