mart1n mart1n - 5 months ago 26
Python Question

Wrapping individual function calls in Python

I'm writing a script that requests some data from an IMAP server using the

library. Having initiated a connection (
), I make the following calls:

rv, data = c.login(EMAIL_ACCOUNT, EMAIL_PASS)
if rv != 'OK':
print('login error')
print(rv, data)

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

rv, data =
if rv != 'OK':
print('folder error')
print(rv, data)

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 (
, etc.). How could I call a select connection function by passing it's name in an argument?

jez jez

To re-use any code, look at the things that stay the same (e.g. the fact that rv and data come out of your imaplib calls in that order, and that rv=='OK' 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 description argument changes the error message:

def check(description, rvdata):
    rv, data = rvdata
    if rv == 'OK':
        return data
        print(description + ' error')
        return None

data = check('login', c.login(EMAIL_ACCOUNT, EMAIL_PASS))
mailboxes = check('mailbox', c.list())
selection = check('folder',