What is a more pythonic way to write this statement?
if soup.find(title="Email"):
profile['email'] = soup.find(title="Email").a.string
What I want to avoid is the repetition of soup.find(title="Email")
-
1Then extract it to a variable; this is not a Python issue, it's the same for pretty much every language going.jonrsharpe– jonrsharpe2016年06月04日 17:01:58 +00:00Commented Jun 4, 2016 at 17:01
2 Answers 2
I do not know if this is more pythonic. I do this with most languages I use. On the top of my head, something like this should avoid the repetition.
soupByEmail = soup.find(title="Email")
if soupByEmail:
profile['email'] = soupByEmail.a.string
2 Comments
profile['email'] = soupByEmail.a.string if soupByEmail else " " Will edit.It's not a matter of pythonic it's more about coding style. And as an elegant alternative you use EAFP principle (Easier to ask for forgiveness than permission) and wrap your snippet with a try-except expression:
try:
profile['email'] = soup.find(title="Email").a.string
except Exception as exp:
# do what you want with exp
Another advantage of this approach is that you can log the issues in your exception block, for later use, or print then in stdout.
3 Comments
find returning a valid object with the appropriate a attribute and (presumably) None. You can do the same here by catching AttributeError, not Exception.