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

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

    Your question focuses on the speed of this operation. First, why do you think this operation is slow? Second, there isn't a faster way to access the attributes. Even trying to avoid the catch by checking for the attribute first will likely be slower, simply because of the Python conditionals needed to check if the attribute exists. Also, hasattr attempts to read the attribute, and catches AttributeError, returning False. So checking for the attribute will actually involve a try/except anyway.

提交回复
热议问题