I frequently use a generator that returns a certain class. What I’d like to do is subclass the generator class so that I can use methods on it that are appropriate for generators that yield instances of that class. For example, one of the things I’d like to do is have a method that returns a generator that filters the base generator.
I want to do something like this:
class Clothes(object):
def __init__(self, generator):
self.generator = generator
def get_red(self):
return (c for c in self.generator if c.color=="red")
def get_hats(self):
return (c for c in self.generator if c.headgear)
The clothes class I want to treat as a collection of clothes. The reason I’m not subclassing a collection is that I rarely want to use the whole collection of clothes as is, and usually just need to filter it further. However, I often need the various filtered collections of clothes. If possible, I’d like Clothes to be a generator itself, as that’s how I intend to use it, but I get an error when trying to subclass types.GeneratorType.
A generator is something that behaves like an iterator, but the sequence it represents is, unlike a tuple or a list, generated lazily for each iteration step. The common ways to create generators are by using generator expressions or with the
yieldstatement; any other mechanism, if it exists, is black magic and you should stay away from it.Therefore, you should forget about
types.GeneratorTypeand inheriting from it. You normally wrap or chain generators together. You can do that with generator expressions, as you have in your example code or you can use the wonderfulitertoolsstandard module.