Search code examples
pythonpython-3.xgeneratorsubclassing

Is there a way to subclass a generator in Python 3?


Aside from the obvious, I thought I'd try this, just in case:

def somegen(input=None):
    ...
    yield
    ...

gentype = type(somegen())
class subgen(gentype):
    def best_function_ever():
        ...

Alas, Python's response was quite hostile:

"TypeError: Type generator is not an acceptable base type"

As luck would have it, that's a problem for me. See, I was thinking that maybe it would be a fun base type to play with, if I gave it a chance. Imagine my surprise! ..and dismay. Is there no way to get the almighty Python to see things my way on this one?

This is most certainly an outside-the-box kinda question, so please don't just say that it's not possible if you can't think of a way immediately. Python (especially Py3) is very flexible.

Of course, if you have evidence of why it cannot (not "should not") be a base type (Py3), then I do want to see and understand that.


Solution

  • You cannot subclass a generator that is defined as a function using yield, but you can use it in another generator.

    Just take this simple one :

    def alphagen(n=27):
        if n<0 or n > 27: n = 27
        for i in range(n):
            yield chr(ord('A') + i)
    

    You get :

    >>>> [ a for a in alphagen(10)]
    ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
    

    You can use it in:

    def alphastartgen(n=27):
        resul = ""
        for i in alphagen(n):
            resul += i
            yield resul
    

    And now you get :

    >>> [ a for a in alphastartgen(8) ]
    ['A', 'AB', 'ABC', 'ABCD', 'ABCDE', 'ABCDEF', 'ABCDEFG', 'ABCDEFGH']