MRAB <pyt...@mrabarnett.plus.com> writes:

> On 2019-05-24 09:25, Cecil Westerhof wrote:
>> Dennis Lee Bieber <wlfr...@ix.netcom.com> writes:
>>
>>> On Fri, 24 May 2019 07:49:23 +0200, Cecil Westerhof <ce...@decebal.nl>
>>> declaimed the following:
>>>
>>>>
>>>>I did not do that consciously, because I have to try until it is
>>>>successful an I return, or I reached the max tries and re-raise the
>>>>exception. With a for loop I could exit the loop and cannot re-raise
>>>>the exception.
>>>
>>>     Your /success/ branch exits the loop by executing a "return" statement.
>>>
>>>     Your /fail/ branch exits the loop by "raise" on the third failure.
>>>
>>>     A "for" loop would have the same behavior; you just replace the manual
>>> initialization and increment of the loop counter.
>>>
>>>     for tries in range(max_try):
>>>             try:
>>>                     do something
>>>                     return successful
>>>             except stuff:
>>>                     if tries+1 == max_try:  #since range is 0..max_try-1
>>>                             raise
>>>
>>> You never "fall off the end" of the loop.
>>
>> That is true, but by using a 'while True:' loop it is clear you never
>> fall off the end of the loop. I find this much clearer. And when there
>> is a bug you get into an endless loop instead of fall of the end.
>> Which in my opinion is easier to spot and mend. And endless loop is
>> noticed the moment it goes wrong. Falling of the end could go without
>> an error and will be spotted much later.
>>
> You could print a message or raise an exception after the 'for' loop so
> that if it ever falls off the end of the loop you'll get a nice message
> instead of it just looping forever! :-)
>

Just changing the while loop to a for loop did not make sense to me,
but this does. I now have:
    max_tries = 5
    for current_try in range(1, max_tries):
        try:
            posted = twitter.update_status(status = message,
                                           in_reply_to_status_id = message_id,
                                           trim_user = True)
            return posted['id']
        except TwythonError as e:
            if not 'Temporary failure in name resolution' in e.msg:
                raise
            timed_message('Failed on try: {0} of {1}'.format(current_try, 
max_tries))
            if current_try == max_tries:
                print('Could not get a connection to the internet: exiting')
                deinit(2)
            time.sleep(60)
    raise RuntimeError('Should not get here')

When I do not get an internet connection, I do not do a re-raise
anymore, but just give a message.

The proc deinit does a sys.exit after some cleanup.

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to