concise code (beginner)

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Sep 3 23:13:31 EDT 2007


bambam a écrit :
> I have about 30 pages (10 * 3 pages each) of code like this
> (following). Can anyone suggest a more compact way to
> code the exception handling? If there is an exception, I need
> to continue the loop, and continue the list.
> 
> Steve.
> 
> -----------------------------------
> for dev in devs
>     try:
>         dev.read1()
>     except
>         print exception
>         remove dev from devs


for method_name in ['read1', 'read2', 'read3']:
   for dev in devs:
     try:
       meth = getattr(dev, method_name)
     except AttributeError, e:
       # should not happen, but we want to handle it anyway
       your_code_here()
     else:
       try:
         meth()
       except (SomePossibleException, SomeOtherPossibleException), e:
         print e
         # do what's needed to remove dev from devs
         # paying attention not to screw the looping machinery...

(snip)



More information about the Python-list mailing list