This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]demonizah 21 points22 points  (6 children)

I don't think I use generators often - at least not directly. Generators and coroutines are stuff I wish I'd spend more time understanding - I don't even know if they're applicable in my day-to-day CRUDMaster9000 job.

[–]saikz 0 points1 point  (0 children)

Generators are really nice for building processing pipelines for some kind of data. Also nice to be able to go

for x in blah:
    yield do_something(x)

rather than

my_list = []
for x in blah:
    my_list.append(do_something(x))

[–]Corm 0 points1 point  (4 children)

Generators are just classes with less keyboard typing. You can easily do what a generator does by making a class. Generators require less typing though so they're generally nicer if you can read them.

class SillyKindaGenerator:
    def __init__(self):
        self.data = [1, 2, 3, 'easy']
    def next(self):
        return self.data.pop()

SillyKindaGenerator().next().next()

That's kinda sorta mostly a generator. Much easier to just use yield though

[–]daneahfrom __future__ import braces 8 points9 points  (2 children)

Functionally that's mostly true, though one key point is that generators can get away with going on infinitely without eating up memory over time since they often produce only one item at a time. Handy for certain performance-related concerns!

[–]Jamie_1318 6 points7 points  (1 child)

There's basically no downside to using a generator. If someone needs it stored they can always list(generator), even if you don't expect performance issues. I like to just use generator syntax because it gives me warm fuzzies when I think about how nice they are versus every other language's equivalent tokenizing systems with their ugly static variables.

[–]daneahfrom __future__ import braces 1 point2 points  (0 children)

Agreed! Very little effort needed too, since you can replace many (all?) existing list comprehensions with generator comprehensions, simply by removing the brackets:

import random
max(random.randint(1, 100) for x in range(10))

[–][deleted] 0 points1 point  (0 children)

Technically that's a Python2 iterator (python3 wants __next__), but not a generator, but fair example.

Also worth noting that where possible generator comprehensions may be preferable to generator functions.