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
link|improve this question

60% accept rate
feedback

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']
link|improve this answer
feedback

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.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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