Wrapping individual function calls in Python
<p>I'm writing a script that requests some data from an IMAP server using the <code>imaplib</code> library. Having initiated a connection (<code>c</code>), I make the following calls:</p>

<pre><code>rv, data = c.login(EMAIL_ACCOUNT, EMAIL_PASS)
if rv != 'OK':
    print('login error')
else:
    print(rv, data)

rv, mailboxes = c.list()
if rv != 'OK':
    print('mailbox error')
else:
    print(rv, data)

rv, data = c.select(EMAIL_FOLDER)
if rv != 'OK':
    print('folder error')
else:
    print(rv, data)
</code></pre>

<p>How could I rewrite this to use some sort of a wrapper function to reuse the logic of checking the error code and printing the data? I assume the function would take an error message as an argument and also the command to execute (<code>select</code>, <code>login</code>, etc.). How could I call a select connection function by passing it's name in an argument?</p>

<p>The way I understood you would like to check Decorators for your task. </p>

<pre><code>class Wrapper:
    def __init__(self, error_message):
        self.error_message = error_message

    def __call__(self, wrapped):
        def func(*args, **kwargs):
            rv, data = wrapped(*args, **kwargs)
            if rv=="OK":
                return(rv, data)
            else:
                print(self.error_message)
                return(rv, data)
        return func

@Wrapper("Folder Error")
def select(email_folder):
    return "OK", "OLOLO"

@Wrapper("Folder Error")
def select_err(email_folder):
    return "FAIL", "OLOLO"

print select("")
print select_err("")
</code></pre>

<p>yields </p>

<pre><code>('OK', 'OLOLO')
Folder Error
('FAIL', 'OLOLO')
</code></pre>

<p>You can check reply inside of Wrapper's <code>__call__</code> function and treat it the way you want to. For exampl you can return "False" or raise errors if <code>rv</code> not equals to "OK"</p>

<p>But It might be overly complicated for your case. </p>

python imaplib