I’m often having code written as follows
try:
self.title = item.title().content.string
except AttributeError, e:
self.title = None
Is there a quicker way of dealing with this? a one-liner?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
What exceptions are you getting from
item.title()? The bareexcept(horrible practice!) doesn’t tell us. If it’s an AttributeError (whereitemdoesn’t have atitlemethod, for example),might be the one-liner you seek (but performance won’t be enormously different, mind you;-).
Edit: as the OP entirely changed the question (it was originally just using
self.title(), it’s now usingself.title().content.string, and does specifically catchAttributeErrorrather than using a bareexcept), the previous version of this answer of course doesn’t apply any more. The proper answer now is: attempting a one-liner is an absurd approach, when the chain of attribute references &c keeps growing longer and longer (how many will there be next time, nine? Since they jumped from one to three with the first edit…;-).And with no idea of which of the many elementary operations expressed by that long, Law of Demeter-scoffing chain of references might raise the AttributeError, any attempt at optimization would be flying rather blind, too.