Nested try statements in python?

后端 未结 6 845
感动是毒
感动是毒 2020-12-08 14:16

Is there a nicer way of doing the following:

try:
    a.method1()
except AttributeError:
    try:
        a.method2()
    except AttributeError:
        try:         


        
6条回答
  •  醉梦人生
    2020-12-08 15:03

    A slight change to the second looks pretty nice and simple. I really doubt you'll notice any performance difference between the two, and this is a bit nicer than a nested try/excepts

    def something(a):
        for methodname in ['method1', 'method2', 'method3']:
            try:
                m = getattr(a, methodname)
            except AttributeError:
                pass
            else:
                return m()
        raise AttributeError
    

    The other very readable way is to do..

    def something(a):
        try:
            return a.method1()
        except:
            pass
    
        try:
            return a.method2()
        except:
            pass
    
        try:
            return a.method3()
        except:
            pass
    
        raise AttributeError
    

    While long, it's very obvious what the function is doing.. Performance really shouldn't be an issue (if a few try/except statements slow your script down noticeably, there is probably a bigger issue with the script structure)

提交回复
热议问题