Object-oriented philosophy

MRAB python at mrabarnett.plus.com
Fri Sep 7 16:48:39 EDT 2018


On 2018-09-07 21:08, Michael F. Stemper wrote:
> On 2018-09-07 14:51, Michael F. Stemper wrote:
>> On 2018-09-06 16:00, MRAB wrote:
>>> On 2018-09-06 21:24, Michael F. Stemper wrote:
> 
>>> A word of advice: don't use a "bare" except, i.e. one that doesn't
>>> specify what exception(s) it should catch.
> 
>> In another case where I had a "bare exception", I was using it to see if
>> something was defined and substitute a default value if it wasn't. Have
>> I cleaned this up properly?
>> 
>>  try
>>    id = xmlmodel.attrib['name']
>>  except KeyError:
>>    id = "constant power"
> 
> Never mind! After I continued testing, I realized that the above
> should have been written as:
> 
>    if 'name' in xmlmodel.attrib:
>      id = xmlmodel.attrib['name']
>    else:
>      id = "constant power"
> 
> <facepalm>
> 
That's actually _less_ Pythonic.

Have a look at the entries "EAFP" and "LBYL" here:

https://docs.python.org/3/glossary.html



More information about the Python-list mailing list