Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a generator or return a generator?

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?

like image 448
Hyperboreus Avatar asked Dec 15 '13 05:12

Hyperboreus


People also ask

What does a generator return?

Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time).

What is the return type of a generator?

A generator is a special type of function which does not return a single value, instead, it returns an iterator object with a sequence of values.

Does generator function has a return statement?

A return statement in a generator, when executed, will make the generator finish (i.e. the done property of the object returned by it will be set to true ). If a value is returned, it will be set as the value property of the object returned by the generator.


1 Answers

Generator comprehensions (such as in g()) would be slightly faster.

Explicit loops (such as in f()) would probably be more readable if your logic beccomes more complex than in the simple example you provided.

Other than that, I can't think of any material differences.

But remember what they say:

Premature optimization is the root of all evil!

like image 186
shx2 Avatar answered Oct 08 '22 21:10

shx2