Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a nice way to handle exceptions in Python?

I have a bunch of code that looks similar to this:

                try:
                    auth = page.ItemAttributes.Author
                except:
                        try:
                            auth = page.ItemAttributes.Creator
                        except:
                                auth = None

Is there a nicer way to write out this logic? This makes my code really painful to read. I thought try..finally would work, but I assumed wrong

like image 633
xporter Avatar asked Jun 24 '10 22:06

xporter


1 Answers

You can use hasattr to avoid the try/except blocks:

auth = None
for attrname in ['Author', 'Creator']:
    if hasattr(page.ItemAttributes, attrname):
        auth = getattr(page.ItemAttributes, attrname)
        break

An alternate way to write the above is to use the else clause of a Python for loop:

for attrname in ['Author', 'Creator']:
    if hasattr(page.ItemAttributes, attrname):
        auth = getattr(page.ItemAttributes, attrname)
        break
else:
    auth = None
like image 151
Mark Byers Avatar answered Oct 30 '22 12:10

Mark Byers