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

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

vs

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


        
12条回答
  •  自闭症患者
    2020-12-01 00:10

    If not having the attribute is not an error condition, the exception handling variant has a problem: it would catch also AttributeErrors that might come internally when accessing obj.attribute (for instance because attribute is a property so that accessing it calls some code).

提交回复
热议问题