[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Object-oriented philosophy

On Fri, 07 Sep 2018 16:07:06 -0500, Michael F. Stemper wrote:

>>> 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"
>>> (Both changes appear to meet my intent, I'm more wondering about how
>>> pythonic they are.)

Yes, catch the direct exception you are expecting. That's perfectly 

>> There's an alternative that's recommended when the key is often absent:
>> ??? id = xmlmodel.attrib.get('name', "constant power")
> Oh, I like that much better than what I showed above, or how I "fixed"
> it cross-thread. Thanks!

However, if the key is nearly always present, and your code is 
performance-critical, calling the "get" method has the slight 
disadvantage that it will be slightly slower than using the try...except 
form you show above.

On the other hand, the get method has the big advantage that it's an 
expression that can be used in place, not a four-line compound statement.

If I don't care about squeezing out every last bit of performance from 
the interpreter, I use whatever looks good to me on the day. That will 
often be the "get" method.

But on the rare occasions I do care about performance, the basic rule of 
thumb I use is that if the key is likely to be missing more than about 
10% of the time, I use the "LBYL" idiom (either an explicit test using 
"if key in dict" or just call the dict.get method).

But don't stress about the choice. Chances are that any of the three 
options you tried (catch KeyError, check with "if" first, or using the 
get method) will be good enough.

Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson