Take the tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

How the following code can be simplified?

  photo = soup.find('div', {'class': 'flagPageTitle'}).nextSibling.find('img') 
  if photo:
      photo = 'http://www.example.com' + photo['src']
  else:
      photo = None
share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

find returns None on failure, so there's no need to set photo to None in the else-branch. If that branch is reached, photo is None already, which makes the assignment redundant.

So you can just write:

photo = soup.find('div', {'class': 'flagPageTitle'}).nextSibling.find('img') 
if photo:
    photo = 'http://www.example.com' + photo['src']
share|improve this answer
add comment

You could do

photo = 'http://www.example.com' + photo['src'] if photo else None

Though ternary operator can be questioned for simplicity. Often it's harder to read code with big ternary operators. Use it with care.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.