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

后端 未结 3 1420
故里飘歌
故里飘歌 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:56

    I believe that the last method is generally preferred by Python coders because of a motto taught in the Python community: "Easier to ask for forgiveness than permission" (EAFP).

    In a nutshell, the motto means to avoid checking if you can do something before you do it. Instead, just run the operation. If it fails, handle it appropriately.

    Also, the third method has the added advantage of making it clear that the operation should work.


    With that said, you really should avoid using a bare except like that. Doing so will capture any/all exceptions, even the unrelated ones. Instead, it is best to capture exceptions specifically.

    Here, you will want to capture for an AttributeError:

    try:
        obj.do_stuff()   # Try to invoke do_stuff
    except AttributeError:
        print 'Do something else'  # If unsuccessful, do something else
    

提交回复
热议问题