MKYJ
MKYJ

Reputation: 11

Python - better solution for loops - Re-run after getting a error & ignore that error after 3 attempts

I created below for loop to run a function to get price data from pandas for a list of tickers. Basically, the loop will re-run the function if getting RemoteDataError and ignore that error after 3 times attempts.

Even though below for loop is working fine for this purpose, I do think there have a better solution since I can not define the times of attempts from below loop, like putting a while loop for times of attempt outside the for loop. I tried to define a variable named attempts = 0, every time it re-run, one attempts will be added. The logic is attempts += 1. If attempts reached 3, use continue to ignore the error. However, it didn't work. Probably I set something wrongly.

 for ticker in tickers:
        print(ticker)
        try:
            get_price_for_ticker()
        except RemoteDataError:
            print('No information for {}'.format(ticker))
            try:
                get_price_for_ticker()
                print('Got data')
            except RemoteDataError:
                print('1st with no data')
                try:
                    get_price_for_ticker()
                    print('Got data')
                except RemoteDataError:
                    print('2nd with no data')
                    try:
                        get_price_for_ticker()
                        print('Got data')
                    except RemoteDataError:
                        print('3rd with no data (should have no data in the database)')
                        continue

Is there a better method for this purpose?

Upvotes: 1

Views: 87

Answers (1)

cs95
cs95

Reputation: 402723

Is there a better method for this purpose?

Yes, there is. Use a while loop and a counter.

count = 0
while count < 3:
    try:
        get_price_for_ticker()
        break                    # reach on success
    except RemoteDataError:
        print('Retrying {}'.format(count + 1)) 
        count += 1               # increment number of failed attempts

if count == 3:
    ...                          # if count equals 3, the read was not successful 

This code should go inside your outer for loop. Alternatively, you could define a function with the while + error handling code that accepts a ticker parameter, and you can call that function at each iteration of the for loop. It's a matter of style, and upto you.

Upvotes: 2

Related Questions