Reputation: 137
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")
Upvotes: 0
Views: 108
Reputation: 192
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
Upvotes: 3
Reputation: 107287
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.
Upvotes: 0