Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested try statements in python?

Is there a nicer way of doing the following:

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

It looks pretty nasty and I'd rather not do:

if hasattr(a, 'method1'):     a.method1() else if hasattr(a, 'method2'):     a.method2() else if hasattr(a, 'method3'):     a.method3() else:     raise AttributeError 

to maintain maximum efficiency.

like image 523
Dan Avatar asked Mar 31 '09 15:03

Dan


People also ask

Can you do nested try statements in Python?

We can have nested try-except blocks in Python. In this case, if an exception is raised in the nested try block, the nested except block is used to handle it. In case the nested except is not able to handle it, the outer except blocks are used to handle the exception.

What is a nested try statement?

As the name suggests, a try block within a try block is called nested try block in Java. This is needed when different blocks like outer and inner may cause different errors. To handle them, we need nested try blocks.

Can you put a try inside except?

If an exception is raised inside the try block, then the except block will get executed but the else block won't.

Can we use two try in Python?

You cannot have that. A try block is not there to suppress exceptions across all code executed. It'll let you catch the exception when it happens, but the rest of the block is never executed.

How do you do nested try/except in NumPy?

A good and simple example for nested try/except could be the following: import numpy as np def divide (x, y): try: out = x/y except: try: out = np.inf * x / abs (x) except: out = np.nan finally: return out Now try various combinations and you will get the correct result:

What is try and except statement in Python?

And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course Try and Except statement is used to handle these errors within our code in Python. The try block is used to check some code for errors i.e the code inside the try block will execute when there is no error in the program.

What is a nested IF statement in Python?

Python nested IF statements. There may be a situation when you want to check for another condition after a condition resolves to true. In such a situation, you can use the nested if construct.

How do you do nesting in Python?

This is done with the help of decision-making statements in Python. We can have an if…elif…else statement inside another if…elif…else statement. This is called nesting in computer programming. Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting.


1 Answers

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)

like image 134
dbr Avatar answered Sep 22 '22 13:09

dbr