Olexiy
Olexiy

Reputation: 1084

Going deeper -- yield from inside yield

Is there a one-liner to take a generator and yield all elements in this generator? For example:

def Yearly(year):
  yield YEARLY_HEADER
  for month in range(1, 13):
    # How can I rewrite the following two lines?
    for line in Monthly(month):
      yield line
  yield YEARLY_FOOTER

def Monthly(month):
  yield MONTHLY_HEADER
  for day in range(31):  # Yes, this is wrong
    yield 'Day %d' % day
  yield MONTHLY_FOOTER

Maybe there are better ways to rewrite this whole method?

Upvotes: 2

Views: 1781

Answers (2)

Jochen Ritzel
Jochen Ritzel

Reputation: 107628

There is no special syntax for this case.

What you want is described in PEP 380. It's been around for years, but I don't think it will make it into Python any time soon. The for .. yield is simple enough and the other changes it proposes are quite complex.

Upvotes: 3

porgarmingduod
porgarmingduod

Reputation: 7878

import itertools

def Yearly(year):
  return itertools.chain(*[(YEARLY_HEADER,)] + 
                         [Monthly(m) for m in range(1, 13)] + 
                         [(YEARLY_FOOTER,)])

Basically, making the YEARLY_HEADER and YEARLY_FOOTER into iterators, they can be chained with the monthly iterators.

Upvotes: 5

Related Questions