xmx
xmx

Reputation: 137

Create method from existing python code

I have this bit of code part of a python script i have to query ldap attributes of users:

try:
    ldap_result_id = l.search(baseDN, searchScope, get_searchFilter(adname), 
retrieveAttributes)
    result_set = []
    while 1:
        result_type, result_data = l.result(ldap_result_id, 0)
        if (result_data == []):
            break
        else:
            ## you could do whatever you want with the individual entry
            ## The appending to list is just for illustration.
            if result_type == ldap.RES_SEARCH_ENTRY:
                result_set.append(result_data)
    for x in result_set:
        print x
except ldap.LDAPError, e:
    print e
    print ldap.LDAPError

How can I clean this up and make it into a reusable function(or is Method the more proper terminology)?

Upvotes: 0

Views: 59

Answers (1)

AChampion
AChampion

Reputation: 30258

Identify the variables that can change and make those arguments to a function. Leave the printing and exception handling outside of the function unless you can do something sensible with the exception:

def fn(baseDN, searchScope, adname, retrieveAttributes):
    ldap_result_id = l.search(baseDN, searchScope, get_searchFilter(adname), 
retrieveAttributes)
    result_set = []
    while 1:
        result_type, result_data = l.result(ldap_result_id, 0)
        if (result_data == []):
            break
        else:
            ## you could do whatever you want with the individual entry
            ## The appending to list is just for illustration.
            if result_type == ldap.RES_SEARCH_ENTRY:
                result_set.append(result_data)
    return result_set

baseDN = ???
searchScope = ???
adname = ???
retrieveAttributes = ???
try:
    for x in fn(baseDN, searchScope, adname, retrieveAttributes):
        print x
except ldap.LDAPError, e:
    print e
    print ldap.LDAPError

Upvotes: 1

Related Questions