when we look at the Python documentation we could see that generators are always defined using yield statement, but in the Internet we could see that some people are trying to implement generators using classes (eg. here How to write a generator class?).
Here is example generator implementation using classes:
from collections import Generator
class Fib(Generator):
def __init__(self):
self.a, self.b = 0, 1
def send(self, ignored_arg):
return_value = self.a
self.a, self.b = self.b, self.a+self.b
return return_value
def throw(self, type=None, value=None, traceback=None):
raise StopIteration
When we execute it in repl we can see it is not the generator, but ordinary object. It only tries to behave like generator.
>>> x = Fib()
>>> x
<__main__.Fib object at 0x7f05a61eab70>
When we look at PEP 342:
- Add a close() method for generator-iterators, which raises GeneratorExit at the point where the generator was paused.
I think it is not possible to meet that condition using own implementation with classes.
Am I wrong? Is it really possible to implement real generator using classes?