Search code examples
pythongeneratoryield

Yield then convert to a list, or returning a list directly?


My current code is like this:

def generateRaw(self, word):
    for entry in self.entries:
        if word in html.unescape(etree.tostring(entry).decode('utf8')):
            yield xmltodict.parse(etree.tostring(entry))

def getRaw(self, word):
    return list(self.generateRaw(word))

Of course, I can just:-

def getRaw(self, word):
    result = []
    for entry in self.entries:
        if word in html.unescape(etree.tostring(entry).decode('utf8')):
            result += [xmltodict.parse(etree.tostring(entry))]
    return result

But, what is a good practice? What is a better way?

Also, recently, I find out that I can use a decorator to convert this, but I haven't really try it out yet:-

def iter2list(func):
    def wrapped(*args):
        return list(func(*args))
    return wrapped

@iter2list
...

I wonder if there is already a module to do this in the first place?


Solution

  • The short answer is probably not, unless someone has created a module which includes the function iter2list. A "module" solution in this case won't make the task easier or more efficient.

    You've already identified two good ways of exhausting a generator in a single list.

    I prefer the decorator method when the generator is designed to be exhausted when used, otherwise use list(mygen()). Syntactically, I find generators more readable, so I don't usually explicitly instantiate a list and fill it.