python isinstance vs hasattr vs try/except: What is better?

后端 未结 3 1418
故里飘歌
故里飘歌 2020-12-09 17:00

I am trying to figure out the tradeoffs between different approaches of determining whether or not with object obj you can perform action do_stuff()

3条回答
  •  离开以前
    2020-12-09 17:33

    Checking with isinstance runs counter to the Python convention of using duck typing.

    hasattr works fine, but is Look Before you Leap instead of the more Pythonic EAFP.

    Your implementation of way 3 is dangerous, since it catches any and all errors, including those raised by the do_stuff method. You could go with the more precise:

    try:
        _ds = obj.do_stuff
    except AttributeError:
        print('Do something else')
    else:
        _ds()
    

    But in this case, I'd prefer way 2 despite the slight overhead - it's just way more readable.

提交回复
热议问题