There is no such method, and you cannot add attributes to the generator. A workaround would be to create an iterator object that wraps your generator and contains the attribute "current". Taking this extra step is to use it as a decorator on a generator.
Here is the utility decorator class that does this:
class with_current(object):
def __init__(self, generator):
self.__gen = generator()
def __iter__(self):
return self
def __next__(self):
self.current = next(self.__gen)
return self.current
def __call__(self):
return self
Then you can use it as follows:
@with_current
def gen():
x=range(0,100)
for i in x:
yield i
a = gen()
print(next(a))
print(next(a))
print(a.current)
Outputs:
0
1
1
source
share