News for hackers. Stuff that matters.
Re:A Python Guide for the Ages by dr_kiszonka on Saturday December 25, 2021 @03:07AM (#29681400)
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/

Re:A Python Guide for the Ages by quietbritishjim on Saturday December 25, 2021 @06:02AM (#29682238)
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.

Re:A Python Guide for the Ages by housecarpenter on Monday December 27, 2021 @12:15AM (#29699521)
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.