Thomas De Bonnet
Thomas De Bonnet

Reputation: 116

Loop over a python function if it has a return value

I'm trying to loop over a function if it has a return value.

So basically when i get the latest orders, sometimes i get a "Next Token". I return this next token if there is one. But then i want to redo the function.

This is how i do it:

    next_token = add_amazon_orders(xml_data=xml_data)
    if next_token:
        next_token = add_amazon_orders(xml_data=auth.list_orders(next_token=next_token['$']))
    if next_token:
        next_token = add_amazon_orders(xml_data=auth.list_orders(next_token=next_token['$']))
        if next_token:
            next_token = add_amazon_orders(xml_data=auth.list_orders(next_token=next_token['$']))

But in the future i might be returning more next tokens and i don't want to keep adding more if functions like this. It's ugly and redundant.

I would prefer something like this:

    next_token = add_amazon_orders(xml_data=xml_data)

    while next_token:
        next_token = add_amazon_orders(xml_data=auth.list_orders(next_token=next_token['$']).original)

But this doesn't work because the while loop stops even if there is a next_token inside it's function.

What would be the best way to achieve this?

Thank you

Upvotes: 0

Views: 145

Answers (1)

x3l51
x3l51

Reputation: 731

Sorry I’m on mobile so not formatting but:

while True:
    if nextToken:
        #Your code here
    else:
        break

Upvotes: 1

Related Questions