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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With