for...else

Jean-Michel Pichavant jeanmichel at sequans.com
Tue Jun 2 09:46:55 EDT 2015


----- Original Message -----
> From: "acdr" <mail.acdr at gmail.com>
> To: "Jean-Michel Pichavant" <jeanmichel at sequans.com>
> Cc: python-list at python.org
> Sent: Tuesday, 2 June, 2015 2:52:21 PM
> Subject: Re: for...else
> 
> That would work for my example, but it would only really work if all
> the calculations are in a nice function. 

You cannot blame me for considering the example you provided ;)

What about this:

class Cleanup(Exception): pass

try:
  for x in it:
    if c1():
      raise Cleanup()
    c2()
    if c3():
      raise Cleanup()
except Cleanup:
  #do the cleanup
   pass

If you can make c1 c3 raise themselves Cleanup, it's even better.

Now if you're able to write a cleanup function that can handle the case when there's nothing to clean, everything becomes crystal clear:

from contextlib import contextmanager

@contextmanager
def cleanup():
  yield
  # here do the cleaning
  print 'I am cleaning'

def do_the_job():
  if c1() : return
  c2()
  if c3() : return

with cleanup():
  do_the_job()

JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you.


More information about the Python-list mailing list