Ruby generators vs Python generators Ruby generators vs Python generators ruby ruby

Ruby generators vs Python generators


This documentation for the rewind method is a little scarce on details. But in order to "start over" the generator would have to do one of two things:

  • remember its complete output, repeat that output once rewound, then resume what it was doing before
  • reset its internal state in a way that causes the same output to be repeated without other unwanted side effects

The second of these is not always possible; for example, if the generator emits byte buffers from the network, the output is not entirely a function of internal state. But any generator that uses the first technique must necessarily build up a larger and larger buffer in memory as it is used. Such generators offer little performance benefit over lists.

Therefore, I conclude that the Ruby rewind method must be optional and not always supported by a concrete enumerator class. So if the Python designers value the Liskov substitution principle, that would lead them not to require such a method in all generators.


Generators are stack based, Ruby's Enumerators are often specialised (at the interpreter level) and not stack based.


Ruby's Enumerator's use StopIteration class internally, see How do Enumerators work in Ruby 1.9.1?

(it's just wrapped if you use it in a for each call). So I'd say they'are a rather close. That being said, I'm not sure what a close method on an enumerator should do, exactly...cleanup, perhaps? (Python's generators probably would benefit from a rewind--note well that in Ruby, some enumerators don't respond to rewind, so they raise an exception when you call that method).