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

前端 未结 12 2327
庸人自扰
庸人自扰 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:02

    At least when it is up to just what's going on in the program, leaving out the human part of readability, etc. (which is actually most of the time more imortant than performance (at least in this case - with that performance span), as Roee Adler and others pointed out).

    Nevertheless looking at it from that perspective, it then becomes a matter of choosing between

    try: getattr(obj, attr)
    except: ...
    

    and

    try: obj.attr
    except: ...
    

    since hasattr just uses the first case to determine the result. Food for thought ;-)

提交回复
热议问题