mart1n mart1n - 2 months ago 14
Python Question

Wrapping individual function calls in Python

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

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

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)


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

jez jez
Answer

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':
        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))