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")
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")
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
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.
find returning a valid object with the appropriate a attribute and (presumably) None. You can do the same here by catching AttributeError, not Exception.