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

后端 未结 6 998
执笔经年
执笔经年 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:20

    • You should know ahead of time whether or not an object has a given attribute. It is a bad sign when you have an object but do not know what it is.

    • You retrieve three attributes in your try block. A try block should contain as little code as possible. You could let an error pass silently if a different attribute is missing than you think.

    • getattr lets you have a default value, but typically should not be used for this purpose.

提交回复
热议问题