Python: All about generators
Generators are very powerful in Python. Its created using 'yield' within the function.
Here are three most important variants, where 'yield' makes a function a generator, a coroutine or as a context manager: [Will explain each when i get time :) ]
A. Using 'Yield' as a generator in function:
def mygen(a=0, b=1):
A. Using 'Yield' as a generator in function:
def mygen(a=0, b=1):
while True:
yield b
a, b = b, a + b
c = mygen()
for i in range(10):
print(c.next())
B. Using 'Yield' as co-routine:
B. Using 'Yield' as co-routine:
def mycoroutine():
v_count = 0 inv_count = 0
try:
try:
while True:
myinput = yield
if isinstance(myinput, int):
if isinstance(myinput, int):
v_count = v_count + 1
else:
else:
inv_count = inv_count + 1
except GeneratorExit:
except GeneratorExit:
print("You Sent {} valid digits and {} invalid chars:".format(v_count,inv_count))
mygen = mycoroutine()
mygen.next()
for i in range(10)+ list("Invalidchars"):
mygen.send(i)
C. Using 'Yield' as context manager
mygen.send(i)
C. Using 'Yield' as context manager
from contextlib import contextmanager
@contextmanager
def function_as_contxmgr(object):
try:
object.counts +=1
yield
finally:
yield
finally:
object.counts -=1
class MyContext:
def __init__(self, arg):
self.counts = arg
myobj = MyContext(10)
with function_as_contxmgr(myobj):
print(myobj.counts)
print(myobj.counts)
Comments