How to implement retrying a lock tidily in Python?

tinnews at isbd.co.uk tinnews at isbd.co.uk
Sun Oct 17 15:02:26 EDT 2010


Matteo Landi <landimatte at gmail.com> wrote:
> On Sun, Oct 17, 2010 at 6:58 PM,  <tinnews at isbd.co.uk> wrote:
> > I'm writing some code that writes to a mbox file and want to retry
> > locking the mbox file a few times before giving up.  I can't see a
> > really tidy way to implement this.
> >
> > Currently I have something like:-
> >
> >    dest = mailbox.mbox(mbName, factory=None)
> >
> >    for tries in xrange(3):
> >        try:
> >            dest.lock()
> >            #
> >            #
> >            # Do some stuff to the mbox file
> >            #
> >            dest.unlock()
> >            break       # done what we need, carry on
> >
> >        except mailbox.ExternalClashError:
> >            log("Destination locked, try " + str(tries))
> >            time.sleep(1)
> >            # and try again
> >
> > ... but this doesn't really work 'nicely' because the break after
> > dest.unlock() takes me to the same place as running out of the number
> > of tries in the for loop.  I need a way to handle the case where we
> > run out of tries (and *haven't* done what we needed to do) separately
> > from the case where it worked OK.
> >
> > I can see all sorts of messy ways to handle this with a flag of some
> > sort but is there a proper elegant way of doing it?
> >
> You can use the 'else' keyword outside the for loop:
> 
> for <condition>:
>   if <condition>:
>     break
> else
>   <some operations>
> 
> The execution will step inside the else branch if the for loop ends
> normally, i.e. without encountering a break keyword.
> Hope it helps.
> 
Thank you!  I'd looked at 'else' inside the 'try' but hadn't thought
of looking at the 'else' that goes with 'for'.  That does just what I
need. 

-- 
Chris Green



More information about the Python-list mailing list