0

The following code is transformed into a generator by the Python compiler:

def myGenerator(max):
  for i in range(max):
    yield i

It can be used with this code:

>>> gen = myGenerator(10)
>>> next(gen)
0
>>> next(gen)
1

If I query the class of gen, I get generator.

Is it possible to use a custom generator class? Let's say I would like to have a percent property on gen.

>>> gen.Percent
10

As far as I have understood generators, they implement several methods. Can I build a generator like object by myself and extend it by custom methods?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Paebbels
  • 15,573
  • 13
  • 70
  • 139
  • 1
    Yes, of course; see https://docs.python.org/3/library/stdtypes.html#typeiter – jonrsharpe Mar 06 '16 at 20:15
  • I'm using these generators in a co-routine based parser. So my parser uses `gen.send(..)` to send tokens to the co-routine. Implementing the iterator protocol by hand does not offer the co-routine feature, does it? – Paebbels Mar 06 '16 at 21:07
  • 1
    You can implement `__aiter__` if you're using `asyncio` - https://docs.python.org/3/reference/datamodel.html#asynchronous-iterators. – jonrsharpe Mar 06 '16 at 21:08
  • Is this [PEP 0492](https://www.python.org/dev/peps/pep-0492/) related? So this feature is available since Python 3.5? – Paebbels Mar 06 '16 at 21:14

0 Answers0