hasattr() vs try-except block to deal with non-existent attributes

前端 未结 12 2321
庸人自扰
庸人自扰 2020-11-30 23:29
if hasattr(obj, \'attribute\'):
    # do somthing

vs

try:
    # access obj.attribute
except AttributeError, e:
    # deal with Attr         


        
12条回答
  •  情深已故
    2020-11-30 23:55

    I'd suggest option 2. Option 1 has a race condition if some other thread is adding or removing the attribute.

    Also python has an Idiom, that EAFP ('easier to ask forgiveness than permission') is better than LBYL ('look before you leap').

提交回复
热议问题