Search code examples
pythonpython-3.xgeneratoryield

Is there a pretty way to yield if in Python 3.3?


Is there a way to make this code prettier?

strong = li.find_all("strong")
if strong:
  yield li.find_all("strong")

I mean something like this:

strong = li.find_all("strong")
yield li.find_all("strong") if strong

Solution

  • You'd use:

    strong = li.find_all("strong")
    if strong:
        yield strong
    

    instead of calling find_all() again (which, in BeautifulSoup, gives the same result but does the work again).

    There is no 'conditional yield'. You could play tricks with yield from but I'd recommend against that.