Faster than trying and except? - Python

I often have code written as follows

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

Is there a faster way to handle this? single line?

+3
source share
6 answers

What exceptions do you get from item.title()? Naked except(terrible practice!) Doesn’t tell us. If it is an AttributeError (where itemthere is no method title, for example),

self.title = getattr(item, 'title', lambda: None)()

may be the one liner you are looking for (but the performance will not differ from you, -).

: OP ( self.title(), self.title().content.string, AttributeError, except), , , . : , & c ( , ? ...; -).

, , , - AttributeError, .

+6

, Id 5% .

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

, AttributeError string:

self.title = getattr(item.title().content, 'string', None)
+2
  • , . , , , .

  • try. try . , , .

  • getattr , .

0

. -, , ? -, . , , , - Python, . , hasattr AttributeError, False. try/except anyway.

0

?

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

, , .

0

Source: https://habr.com/ru/post/1736907/


All Articles