0

I just want to minify the rows of the code. I have two loops with the only difference two lines. Is it possible (functions or classes) to change the lines in each occasion? The two loops are:

cursor = ''
while True:
    data =  API_like_query(id,cursor)
    #more code
    for i in data['data']:
        ids_likes += i['id']+' , '
    #more code

and

cursor = ''
while True:
    data =  API_com_query(id,cursor)
    #more code
    for i in data['data']:
        ids_likes += i['from']['id']+' , '
    #more code

More code is the same chunk of code used. The difference is in the function call (line 3) and the different dictionary object in line 6.

1
  • 1
    Different optimization that you asked for, but is ids_likes just a string with IDs joined by ' , '? Then you should use ' , '.join(lst) Commented Aug 7, 2013 at 13:57

3 Answers 3

3

You can create a function quite easily:

def do_stuff(api_func, get_data_func):
    cursor = ''
    while True:
        data = api_func(id, cursor)
        #more code
        for i in data['data']:
            ids_likes += get_data_func(i) + ', '
        #more code

Then the first loop can be reproduced with:

do_stuff(API_like_query, lambda i: i['id'])

And the second one:

do_stuff(API_come_query, lambda i: i['from']['id'])

Functions are made to divide code into smaller, more easily testable and reusable pieces, so it seems appropriate in this case.

Sign up to request clarification or add additional context in comments.

3 Comments

Even neater than lambdas would probably be to use operator.itemgetter to construct the getter functions. Other than that, this is by far the cleanest approach in my opinion.
@LukasGraf The first one can be easily replaced with itemgetter, but the nested access of the second case isn't easily replaced. you have to use partial or lambda anyway.
Indeed, just realized that when playing around with them myself. +1 for mentioning functools.partial, didn't know about that! :)
0

joinedquery=izip(API_like_query(id,cursor),API_com_query(id,cursor)) if query length the same. then for i1,i2 in joinedquery:

Comments

-1

You can put everything into a function with an argument which way to use:

def do_something(which_query):
    cursor = ''
    while True:
        if which_query == 1:
            data =  API_like_query(id,cursor)
        elif which_query == 2:
            data =  API_com_query(id,cursor)
        #code
        for i in data['data']:
            if which_query == 1:
                ids_likes += i['id']+' , '
            elif which_query == 2:
                ids_likes += i['from']['id']+' , '
        #more code

But the additional if's only make the code shorter not faster!

Comments

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.