I've been researching the similarities/differences between Ruby and Python generators (known as Enumerators
in Ruby), and so far as i can tell they're pretty much equivalent.
However one difference i've noticed is that Python Generators support a close()
method whereas Ruby Generators do not. From the Python docs the close()
method is said to do the following:
Raises a GeneratorExit at the point where the generator function was paused. If the generator function then raises StopIteration (by exiting normally, or due to already being closed) or GeneratorExit (by not catching the exception), close returns to its caller."
Is there a good reason why Ruby Enumerators
don't support the close()
method? Or is it an accidental
omission?
I also discovered that Ruby Enumerators
support a rewind()
method yet Python generators do not...is there a reason for this too?
Thanks
Ruby provides a script called Generator. This script can be used to generate many useful items in Rails.
Generators in python provide an efficient way of generating numbers or objects as and when needed, without having to store all the values in memory beforehand.
Generators are great when you encounter problems that require you to read from a large dataset. Reading from a large dataset indirectly means our computer or server would have to allocate memory for it. The only condition to remember is that a Generator can only be iterated once.
Generators have been an important part of Python ever since they were introduced with PEP 255. Generator functions allow you to declare a function that behaves like an iterator. They allow programmers to make an iterator in a fast, easy, and clean way.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With