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

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

    Any benches that illustrate difference in performance?

    timeit it's your friend

    $ python -mtimeit -s 'class C(object): a = 4
    c = C()' 'hasattr(c, "nonexistent")'
    1000000 loops, best of 3: 1.87 usec per loop
    $ python -mtimeit -s 'class C(object): a = 4
    c = C()' 'hasattr(c, "a")'
    1000000 loops, best of 3: 0.446 usec per loop
    $ python -mtimeit -s 'class C(object): a = 4
    c = C()' 'try:
     c.a
    except:
     pass'
    1000000 loops, best of 3: 0.247 usec per loop
    $ python -mtimeit -s 'class C(object): a = 4
    c = C()' 'try:
     c.nonexistent
    except:
     pass'
    100000 loops, best of 3: 3.13 usec per loop
    $
    
           |positive|negative
    hasattr|  0.446 |  1.87 
    try    |  0.247 |  3.13
    

提交回复
热议问题