[Tutor] Try except really better than if?

Steven D'Aprano steve at pearwood.info
Mon Jan 10 11:32:28 CET 2011


Karim wrote:
> 
> Thank you Steven, Modulok and Alan for your precious and detailed 
> explanations!
> 
> I understood that I must not overuse try-except statement and usually 
> when the exception could happen exceptionally.
> By the way I have this piece of code using elementTree standard module 
> and according to Alan this is bad code I guess:
> 
> *try: devdb.setDescription(dev.attrib['description'])
> except KeyError: pass
[...]

Whenever you have very similar code repeated many times, you should 
consider factoring out the common code into a helper function. Something 
like this:

def try_or_pass(key):
     attr_name = 'set' + key[0].upper() + key[1:]
     try:
         getattr(devb, attr_name)(dev.attrib[key])
     except KeyError:
         pass

try_or_pass('description')
try_or_pass('symbolName')
etc.



-- 
Steven



More information about the Tutor mailing list