Write a generator or return a generator?

Viewed 138

Inside a container class, when I want to iterate over its items (or transformations of its items, or a subset of its items), I can either write a generator (like f) or return a generator (like g):

class SomeContainer:
    def __init__(self):
        self.data = [1, 'two', 3, 'four']

    def f(self):
        for e in self.data: yield e + e

    def g(self):
        return (e + e for e in self.data)

sc = SomeContainer()
for x in sc.f(): print(x)
for x in sc.g(): print(x)

I do not need to pass information into the generator via send.

Apparently both ways behave identical (at the surface).

  1. Which approach is preferable and why?

  2. Which approach creates less overhead or has other advantages I fail to spot?

1 Answers
Related