https://medium.com/python-in-plain-english/10-surprising-ways-to-use-generators-in-python-426a38a0d5eb
Generating Infinite Sequences
def natural_number():
n = 1
while True:
yield n
n += 1
for num in natural_number():
print(num)
if num >= 10:
break
nat = natural_number()
for _ in range(10):
print(next(nat))
Generating Large Fibonacci Sequences
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
f = fibonacci()
for _ in range(10):
print(next(f))
Tracking with Generator.send() Method
def tracker():
while True:
x = yield
print(f"Tracked: {x}")
t = tracker()
next(t) # yield 까지 수행
t.send("Hello")
t.send("World")
# Tracked: Hello
# Tracked: World
Streaming Large CSV Files
import csv
def csv_reader(file_name):
for row in csv.reader(open(file_name)):
yield row