Quicker way than “try” and “except” ? - Python

后端 未结 6 991
执笔经年
执笔经年 2021-01-14 07:39

I\'m often having code written as follows

try:
  self.title = item.title().content.string
except AttributeError, e:
  self.title = None

6条回答
  •  孤城傲影
    2021-01-14 08:25

    In one line, although I’d only recommend this in 5% of all use cases.

    self.title = item.title().content.string if hasattr(item, 'title') else None
    

提交回复
热议问题