0

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)?

3
  • Since you do not intend to produce classes, "function" is the more proper and the only right terminology. Commented Apr 19, 2017 at 5:53
  • @DYZ In the event i start to use classes would it then be a Method? Commented Apr 19, 2017 at 14:56
  • Only if it is a part of the class. Commented Apr 19, 2017 at 14:57

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

I assume the baseDN = ???, searchScope = ???,adname = ??? and retrieveAttributes = ??? should be omitted from the script?
Those are variables that need to be provided, e.g. user input, read from a data store, passed by another application, etc.
gotcha! Yes, i have those already provided in my python script in another section! Your solution worked wonderfully!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.