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>To re-use any code, look at the things that stay the same (e.g. the fact that <code>rv</code> and <code>data</code> come out of your <code>imaplib</code> calls in that order, and that <code>rv=='OK'</code> means things are OK) and write the logic that involves them, once. Then look at the things that change (e.g. the exact error message that needs to be printed). Parameterize the things that change, as in this example where the <code>description</code> argument changes the error message:</p>

<pre><code>def check(description, rvdata):
    rv, data = rvdata
    if rv == 'OK':
        print(data)
        return data
    else:
        print(description + ' error')
        return None

data = check('login', c.login(EMAIL_ACCOUNT, EMAIL_PASS))
mailboxes = check('mailbox', c.list())
selection = check('folder', c.select(EMAIL_FOLDER))
</code></pre>

python imaplib