Hacker News new | ask | show | jobs
by dr_kiszonka 1641 days ago
I find generators useful when working with very large data structures because generators can be pretty efficient. You can also use them to write little helper functions. Have a look at this package and its source [0]. Oh, and don't feel bad if you never have a need for generators! For the longest time I felt like a steal for rarely using classes but I am over it now :)

0. https://more-itertools.readthedocs.io/en/stable/

1 comments

They didn't say they hadn't used generators at all. They said they hadn't made use of "returning a value from a generator" which is different from the usual method of yielding from them.

    def my_generator():
        yield 1
        yield 2
        return 3
If you use that generator in a for loop then it will only put 1 and 2 into the iterator variable. You have to use the generator in a more direct way to get access to the 3.

I haven't made use of return values from generators in my code either, but I believe they're used under the hood in coroutines in async code.

I used generators with return values once when writing a lexer. I had generators for each of a bunch of different states of the lexer (e.g. skipping over whitespace, reading a numeric literal, reading a string literal, etc.). Each generator would yielded the tokens that it could and then either return one of the other generators (if a state transition was required) or None (if it reached the end of the input and the state was one where this wasn't an error condition). The whole thing was tied together with this function:

  def lex(src):
    state = skip_whitespace

    while state is not None:
      state = yield from state()
It wasn't particularly essential to use the return value from the generator here, as I could have just made the state variable available in the scope of the state functions for them to mutate, but this seemed like a cleaner way to do it as it enforced the idea that each new state corresponded to a new function.