0

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")

1
  • 1
    Then extract it to a variable; this is not a Python issue, it's the same for pretty much every language going. Commented Jun 4, 2016 at 17:01

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

You used two ifs and even if you didn't it wouldn't be valid. You're thinking of Ruby.
@AlexHall Ah yes, this only works if there is an else condition as well. profile['email'] = soupByEmail.a.string if soupByEmail else " " Will edit.
0

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

The original code specifically distinguished between find returning a valid object with the appropriate a attribute and (presumably) None. You can do the same here by catching AttributeError, not Exception.
@chepner Maybe, but since there would be a lot of exception in that line, I can't rely on what I'm not sure about 100%, also OP doesn't explained the code completely.
"Optimizing" generally means the OP is asking for code that does the same thing as their code, and this does not meet that requirement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.