In Python I can build a generator like so:
def gen():
x = range(0, 100)
for i in x:
yield i
I can now define an instance of the generator using:
a = gen()
And pull new values from the generator using
a.next()
But is there a way—a.current()
—to get the current value of the generator?
There isn't such a method, and you cannot add attributes to a generator. A workaround would be to create an iterator object that wraps your generator, and contains a 'current' attribute. Taking it an extra step is to use it as a decorator on the generator.
Here's a utility decorator class which does that:
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
You can then use it like this:
@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
You set the value of a variable.
current_value = a.next()
then use current_value for all it's worth. Python uses this often in for statements
a = xrange(10)
for x in a:
print(x)
Here you are defining x as the current value of a.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With