tags: language computer programming-language program

Generators

Special kind of functions which returns a lazy iterator.

For example, a file reader that files lazily.

"file_reader.py"
 
 
def file_reader(filename):
    print('above with')
    with open(filename, 'r') as file:
        print('below with')
        for line in file:
            yield line
            print("after yield")
 

Generator expressions

counter = (num in range(10))

yield

It suspends the execution of the function and returns the yield value to the caller. On next generator method call, it continues executing after the yield.

It saves the state of the function.

Generator methods

  1. .send() : yield is not a statement. It is an expression.
def counter():
	a = 0
	while True:
		b = (yield a)
		print(b)
		a += 1

if we do,

c = counter()
c.send(12)
 
outputs:
0
12
1

12 is assigned to variable b.

  1. .throw() used to throw exception in generator.
  2. .close() to StopIteration

See Also

  1. cProfile