Is it possible to create an attribute on a generator object?
Here’s a very simple example:
def filter(x):
for line in myContent:
if line == x:
yield x
Now say I have a lot of these filter generator objects floating around… maybe some of them are anonymous… I want to go back later and interrogate them for what they are filtering for. Is there a way I can a) interrogate the generator object for the value of x or b) set an attribute with the value of x that I can later interrogate?
Thanks
Unfortunately, generator objects (the results returned from calling a generator function) do not support adding arbitrary attributes. You can work around it to some extent by using an external dict indexed by the generator objects, since such objects are usable as keys into a dict. So where you’d like to do, say:
you may instead do:
For anything fancier, use a class instead of a generator (one or more of the class’s methods can be generators, after all).