Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 938
Inversus Avatar asked Nov 04 '14 14:11

Inversus


1 Answers

A relevant other question is Which classes cannot be subclassed?.

It's reason 2 in the accepted answer there -- subclassing of a type needs to be implemented in C, and it wasn't implemented for generators, probably because nobody saw a use case.

The source code for generator objects is genobject.c, and you can see on line 349 that the Py_TPFLAGS_BASETYPE flag is not set.

like image 142
RemcoGerlich Avatar answered Sep 24 '22 00:09

RemcoGerlich