Is there a good way to handle exceptions in Python?

I have a bunch of code that looks something like this:

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

Is there a better way to write out this logic? This makes my code very painful to read. I thought the attempt ... would finally work, but I was wrong

+6
python exception
source share
3 answers

You can use hasattr to avoid try / except blocks:

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

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

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

This makes my code very painful to read.

Whatever you do, do not use wildcards. except: is the pythonic way of saying: Hey, all exceptions are equal, I want every single error in my try block to end up here, I don't care if I catch an AttributeError or a WorldGotFuckedUpException . In your case, except AttributeError much, much better AND easier to read.

This is just a note. Mark answer shows the best way to do this, IMHO.

+3
source share

@Mark Byers answer is more flexible, but if you want to use single line

 auth = getattr(page.ItemAttributes, 'Author', None) or getattr(page.ItemAttributes, 'Creator', None) 
+2
source share

All Articles