Current value of the generator

In Python, I can build a generator like this:

def gen():
  x=range(0,100)
  for i in x:
    yield i  

Now I can determine the instance of the generator using:

a=gen()

And pull the new values ​​out of the generator with

a.next()

But is there any way --- a.current()--- to get the current value of the generator?

+4
source share
2 answers

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
+7
source

.

current_value = a.next()

current_value , . Python

a = xrange(10)
for x in a:
    print(x)

x a.

+5

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


All Articles