1. 6

  2. 4

    return in a generator throws a StopIteration exception, which is a useful feature but not the same thing as yield from at all. That being said, yield from will also throw a StopIteration exception if the generator it’s yielding from throws one. StopIteration is nothing to be afraid of.

    1. 1

      StopIteration is nothing to be afraid of.

      StopIteration is definitely nothing to be afraid of, but a big change in logic, from a subtle change in code is. Since returning the value doesn’t do anything other than stopping the iteration, I would much rather not even being able to actually return a value (empty return statements are okay). This can be caught by linting, but I can see it easily passing code review if the diff doesn’t include both the return val and the yield.

      1. 2

        You’re right, but I think it’s worth also remembering that return to yield from is really no smaller a change in code than say if to while.

        1. 1

          Yeah that’s quite true.

        2. 1

          In Python 2, a non-empty return inside a generator (any def that yield) would give you a syntax error

          SyntaxError: 'return' with argument inside generator

          So it used to be the way you wanted it. I hadn’t noticed this change in Python 3.

          I have an implementation of an interpreter for (a subset of) Python and I think it would be clearer if a different keyword than def (like gen) was used for generators. This would also mean the interpreter doesn’t need to look inside the body to know if its a function or generator.

          1. 1

            I think the gen can be a good idea, since it would make it also a bit clearer, for the reader. In general I’ve barely had any issues from confusing generators and functions so I guess the main benefit would still be for the interpreter. Also really interesting project you’ve got, the link you posted is broken though and redirects to lobste.rs/github.com/.....

      2. 3

        ops, I neither knew, nor thought about this, thanks for sharing. I don’t believe I’ve ever mixed them in this way, but I’ve definitely had empty return statements to stop. The reason for this it turns out is that the return statement (It seems regardless of what it returns) throws a StopIteration exception when in a generator.

        1. 1

          And the example with just return works because it returns the generator, not the elements.