[Tutor] Try except really better than if?
Karim
karim.liateni at free.fr
Mon Jan 10 11:50:11 CET 2011
Steven many thanks for this useful hint!
I will modify my code.
Many thanks!
Regards
Karim
On 01/10/2011 11:32 AM, Steven D'Aprano wrote:
> 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.
>
>
>
More information about the Tutor
mailing list