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

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

    This subject was covered in the EuroPython 2016 talk Writing faster Python by Sebastian Witowski. Here's a reproduction of his slide with the performance summary. He also uses the terminology look before you leap in this discussion, worth mentioning here to tag that keyword.

    If the attribute is actually missing then begging for forgiveness will be slower than asking for permissions. So as a rule of thumb you can use the ask for permission way if know that it is very likely that the attribute will be missing or other problems that you can predict. Otherwise if you expect code will result in most of the times readable code

    3 PERMISSIONS OR FORGIVENESS?

    # CASE 1 -- Attribute Exists
    class Foo(object):
        hello = 'world'
    foo = Foo()
    
    if hasatter(foo, 'hello'):
        foo.hello
    ## 149ns ##
    
    try:
        foo.hello
    except AttributeError:
        pass
    ## 43.1 ns ##
    ## 3.5 times faster
    
    
    # CASE 2 -- Attribute Absent
    class Bar(object):
        pass
    bar = Bar()
    
    if hasattr(bar, 'hello'):
        bar.hello
    ## 428 ns ##
    
    try:
        bar.hello
    except AttributeError :
        pass
    ## 536 ns ##
    ## 25% slower
    

提交回复
热议问题