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

Besides 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 answer was rather hostile:

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

How lucky this is a problem for me. You see, I thought that perhaps it would be a fun basic type if I gave him a chance. Imagine my surprise! .. and confusion. Is there no way to make almighty Python see something in my way?

This is certainly a question about appearance, so please do not say that it is impossible if you cannot immediately come up with a way. Python (especially Py3) is very flexible.

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

+5
source share
2 answers

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 are getting:

 >>>> [ 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'] 
+1
source

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

The reason 2 is in the accepted answer there - the subclass of the class must be implemented in C, and it was not implemented for generators, probably because no one saw a precedent.

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

+2
source

Source: https://habr.com/ru/post/1206172/


All Articles