ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
ယခင် generator lesson မှာ generator က တစ်လမ်းသွား ပိုက်လိုင်းလိုပါ — value တွေ ထွက်လာရုံပဲ ရှိပါတယ်။ အခု အဲဒါကို ဖုန်းခေါ်ဆိုမှုလို နှစ်လမ်းသွား ဖြစ်အောင် လုပ်ကြည့်ပါမယ်။ Caller က "ဒီ number ကို ထည့်ပါ" (send) လို့ ပြောလို့ရပြီး "ပြန်စပါ" (throw) ဒါမှမဟုတ် "ဖုန်းချပြီ" (close) လို့လည်း ပြောလို့ ရပါတယ်။
နောက်တစ်ခုက ပိုက်လိုင်းတွေကို ဆက်တာပါ။ စက်ရုံ conveyor belt တစ်ခုမှာ ဌာနတစ်ခုက ပစ္စည်းကို သန့်ရှင်းပြီး နောက်ဌာနက စစ်ဆေးကာ နောက်တစ်ခုက ထုပ်ပိုးပါတယ်။ ပစ္စည်း တစ်ခုချင်းစီ ဌာနတိုင်းကို ဖြတ်သွားပြီး ဘယ်ဌာနမှာမှ တောင်ပုံရာပုံ စုမထားပါဘူး။ Generator pipeline ကလည်း ဒီလိုပါပဲ။
Problem → Why → Solution
ပြဿနာ: state ကို global variable နဲ့ ထိန်းထားရတာ
Sensor reading တွေ တစ်ခုချင်း ဝင်လာတိုင်း ပျမ်းမျှကို update လုပ်ချင်တယ် ဆိုပါစို့။ ရိုးရိုးနည်းက total နဲ့ count ကို global variable အဖြစ် ထားပြီး function ထဲမှာ global keyword နဲ့ ပြင်တာပါ။ ဒါပေမယ့် sensor နှစ်ခုအတွက် ပျမ်းမျှ နှစ်ခု လိုလာရင် variable တွေ ရောသွားပြီး reset လုပ်ဖို့ ဘယ်နေရာ ပြင်ရမလဲ မရှင်းပါဘူး။ Test တစ်ခုက ကျန်ခဲ့တဲ့ state ကြောင့် နောက် test က fail ဖြစ်ပါတယ်။
total = 0
count = 0
def add_reading(value):
global total, count # shared by every caller
total += value
count += 1
return total / count
add_reading(10)
add_reading(20)
# A second sensor? A reset? Both mean more globals and more bugs.ဘာကြောင့် generator က ပိုကောင်းတာလဲ
Generator ရဲ့ local variable တွေက yield တွေကြားမှာ ဆက်ရှင်နေပြီး generator object တစ်ခုစီက ကိုယ်ပိုင် state ရှိပါတယ်။ send() နဲ့ value ကို အထဲ ပို့နိုင်ရင် global မလိုဘဲ sensor တစ်ခုစီအတွက် running_average() object တစ်ခုစီ ဆောက်ရုံပါပဲ။ Reset ကိုတော့ throw() နဲ့၊ cleanup ကို close() နဲ့ လုပ်နိုင်ပါတယ်။
Core concept: နှစ်လမ်းသွား generator နဲ့ အလုပ်လွှဲခြင်း
yield က statement သာမက expression လည်း ဖြစ်ပါတယ်။ value = yield average လို့ ရေးရင် generator က average ကို အပြင်ထုတ်ပေးပြီး ရပ်ပါတယ်၊ ဆက်တဲ့အခါ yield expression ရဲ့ value က caller ပို့လိုက်တဲ့ value ဖြစ်ပါတယ်။ next(gen) နဲ့ ဆက်ရင် အဲဒီ value က None ဖြစ်ပြီး gen.send(10) နဲ့ ဆက်ရင် 10 ဖြစ်ပါတယ်။ send() က နောက် yield အထိ run ပြီး အဲဒီ yield ထုတ်ပေးတဲ့ value ကို return ပြန်ပါတယ်။ ဒါပေမယ့် generator အသစ်က yield တစ်ခုမှာ ရပ်မနေသေးလို့ send(10) ကို ချက်ချင်း ခေါ်ရင် "can't send non-None value to a just-started generator" TypeError တက်ပါတယ်၊ ဒါကြောင့် next(gen) နဲ့ ပထမ yield အထိ prime လုပ်ရပါတယ်။
gen.throw(exc) က ရပ်ထားတဲ့ yield နေရာမှာ exception ကို တက်စေပါတယ်။ Generator က try/except နဲ့ ဖမ်းပြီး ဆက်သွားရင် throw() က နောက် yield ရဲ့ value ကို return ပြန်ပြီး မဖမ်းရင် exception က caller ဆီ ပြန်ထွက်လာပါတယ်။ gen.close() ကတော့ ရပ်ထားတဲ့ နေရာမှာ GeneratorExit ကို တက်စေပြီး finally block နဲ့ with block တွေကို run ပေးလို့ file ပိတ်တာ၊ connection ပြန်ပေးတာလို cleanup လုပ်ဖို့ နေရာ ဖြစ်ပါတယ်။ GeneratorExit ကို ဖမ်းပြီး ထပ် yield လုပ်ရင် RuntimeError တက်ပါတယ်။
yield from iterable က for item in iterable: yield item ထက် ပိုလုပ်ပေးပါတယ်။ send(), throw() နဲ့ close() တွေကို sub-generator ဆီ တိုက်ရိုက် ဖြတ်ပို့ပြီး sub-generator က return value နဲ့ ပြီးသွားရင် အဲဒီ value က yield from expression ရဲ့ ရလဒ် ဖြစ်ပါတယ်။ အသုံးအများဆုံးကတော့ generator ကြီးတစ်ခုကို အပိုင်းလေးတွေ ခွဲရေးတာနဲ့ tree လို recursive data ကို ဖြန့်တာပါ။
Generator တစ်ခုက iterable တစ်ခုကို လက်ခံပြီး generator ပြန်ပေးရင် stage တွေကို ဆက်လို့ရပါတယ် — server_errors(parse(lines)) လိုပါ။ အပြင်ဆုံး stage ကို next() တောင်းမှ record တစ်ခုက stage အားလုံးကို ဖြတ်လာပြီး ကျန်တာတွေ မတွက်ရသေးပါဘူး။ itertools module က ဒီ stage တွေအတွက် စမ်းသပ်ပြီးသား အစိတ်အပိုင်းတွေ ပေးပါတယ် — islice က iterator ကို slice လုပ်ပြီး chain က ဆက်ပေးကာ groupby က ကပ်လျက် item တူတွေကို အုပ်စုဖွဲ့ပြီး accumulate က running total ထုတ်ကာ takewhile က condition မမှန်တော့တာနဲ့ ရပ်ပါတယ်။
- next() နဲ့ ပထမ yield အထိ prime
- send(v) က v ကို yield ရလဒ်အဖြစ် ပို့
- throw(e) က yield နေရာမှာ e တက်
- close() က GeneratorExit + finally
Method သုံးခုလုံးက ရပ်ထားတဲ့ yield တစ်ခုတည်းကို ပစ်မှတ်ထားပါတယ်။
အထွေထွေ ပုံစံ
def worker():
try:
while True:
received = yield result # out: result, in: what send() passed
finally:
cleanup() # runs on close()
gen = worker(); next(gen) # prime
gen.send(value); gen.throw(SomeError()); gen.close()
def outer(): yield from inner() # delegate, forwarding send/throw
stage3(stage2(stage1(source))) # lazy pipelineyield ရဲ့ ဘယ်ဘက်က variable က send() ပို့တဲ့ value ကို ရပါတယ်။ finally က close() ခေါ်ရင် run ပါတယ်။ yield from က sub-generator ဆီ အလုပ်လွှဲပြီး နောက်ဆုံး line က stage တွေ ဆက်ထားတဲ့ pipeline ပါ။
Example: running average, flatten, log pipeline နဲ့ itertools
Example မှာ အပိုင်းလေးပိုင်း ပါပါတယ်။ running_average က send(), throw(), close() သုံးခုလုံးကို လက်ခံပြီး flatten က yield from နဲ့ list ထဲက list တွေကို ဖြန့်ပါတယ်။ parse နဲ့ server_errors က log line တွေကို တစ်ကြောင်းချင်း ဖြတ်သွားတဲ့ pipeline ဖြစ်ပြီး နောက်ဆုံး line တွေက itertools function သုံးခုကို ပြပါတယ်။
import itertools
# 1. send(), throw() and close(): a generator that receives values
def running_average():
total = count = 0
average = None
try:
while True:
try:
value = yield average # pause here, receive a value
except ValueError: # raised inside by throw()
total = count = 0
average = None
continue
total += value
count += 1
average = total / count
finally:
print(" cleanup: running_average closed")
avg = running_average()
next(avg) # prime: run to the first yield
print("1. send:", avg.send(10), avg.send(20), avg.send(60))
print("2. throw ->", avg.throw(ValueError("reset")))
print("3. after reset:", avg.send(5))
avg.close()
# 2. yield from delegates to another iterable (here, recursively)
def flatten(items):
for item in items:
if isinstance(item, list):
yield from flatten(item)
else:
yield item
print("4. yield from:", list(flatten([1, [2, [3, 4]], 5])))
# 3. A lazy pipeline: each stage pulls one record at a time
LOG = ["GET /a 200", "GET /b 500", "POST /a 201", "GET /c 503", "GET /a 200"]
def parse(lines):
for line in lines:
method, path, status = line.split()
yield method, path, int(status)
def server_errors(records):
return (r for r in records if r[2] >= 500)
print("5. first error:", next(server_errors(parse(LOG))))
# 4. itertools building blocks
paths = sorted(path for _, path, _ in parse(LOG))
print("6. groupby:", {p: len(list(g)) for p, g in itertools.groupby(paths)})
print("7. islice + count:", list(itertools.islice(itertools.count(1, 3), 4)))
print("8. chain:", list(itertools.chain("ab", [1, 2])))Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Line 11
value = yield average # pause here, receive a valueaverage ကို အပြင်ထုတ်ပြီး ရပ်ပါတယ်။ send(10) နဲ့ ဆက်တဲ့အခါ value က 10 ဖြစ်ပြီး ပေါင်းကာ ပျမ်းမျှ တွက်ပြီးနောက် loop က ဒီ line ကို ပြန်ရောက်လို့ 10.0 ကို send() ရဲ့ ရလဒ်အဖြစ် ထုတ်ပေးပါတယ်။ 10, 20, 60 ပို့ရင် 10.0, 15.0, 30.0 ရပါတယ်။
- Line 24
next(avg)Generator အသစ်ကို ပထမ yield အထိ run စေပြီး None ကို ထုတ်ပေးပါတယ်၊ ဒီ value ကို မသုံးပါဘူး။ ဒီ line မပါရင် နောက် line က send(10) မှာ TypeError တက်ပါတယ်။
- Line 26-28
print("2. throw ->", avg.throw(ValueError("reset")))ValueError က yield နေရာမှာ တက်ပြီး except က total နဲ့ count ကို reset လုပ်ကာ continue နဲ့ yield ကို ပြန်ရောက်ပါတယ်။ အဲဒီ yield က None ထုတ်လို့ throw() က None ပြန်ပါတယ်။ close() က GeneratorExit တက်စေလို့ finally ထဲက cleanup line ကို print ထုတ်ပါတယ်။
- Line 32-37
yield from flatten(item)Item က list ဖြစ်ရင် flatten ကို recursive ခေါ်ပြီး ရလာတဲ့ value အားလုံးကို အပြင်ကို ဖြတ်ပို့ပါတယ်။ Nesting ဘယ်လောက် နက်နက် တစ်ဆင့်ချင်း yield from နဲ့ ဆင့်ပို့လို့ [1, 2, 3, 4, 5] ရပါတယ်။
- Line 53
print("5. first error:", next(server_errors(parse(LOG))))next() က server_errors ဆီ record တစ်ခု တောင်းပြီး server_errors က parse ဆီ တောင်းပါတယ်။ "GET /a 200" က filter မဖြတ်လို့ ဒုတိယ line ကို parse လုပ်ပြီး 500 ကို တွေ့တာနဲ့ ရပ်ပါတယ်၊ ကျန်တဲ့ line သုံးကြောင်းကို ဘယ်တော့မှ split မလုပ်ပါဘူး။
- Line 56-57
itertools.groupby(paths)groupby က ကပ်လျက်ရှိတဲ့ item တူတွေကိုပဲ အုပ်စုဖွဲ့လို့ sorted() နဲ့ အရင်စီထားရပါတယ်။ မစီဘဲ သုံးရင် /a က အုပ်စုသုံးခု ခွဲထွက်ပြီး dict ထဲမှာ နောက်ဆုံး count နဲ့ အစားထိုးခံရပါတယ်။
1. send: 10.0 15.0 30.0
2. throw -> None
3. after reset: 5.0
cleanup: running_average closed
4. yield from: [1, 2, 3, 4, 5]
5. first error: ('GET', '/b', 500)
6. groupby: {'/a': 3, '/b': 1, '/c': 1}
7. islice + count: [1, 4, 7, 10]
8. chain: ['a', 'b', 1, 2]yield from က sub-generator ရဲ့ return value ကို ယူတာ
Generator ထဲမှာ return value ရေးရင် အဲဒီ value က StopIteration.value ထဲ ရောက်ပါတယ်၊ for loop က အဲဒါကို လျစ်လျူရှုပါတယ်။ yield from ကတော့ အဲဒီ value ကို expression ရလဒ်အဖြစ် ပေးလို့ sub-generator တစ်ခုက value တွေ yield ပေးရင်း နောက်ဆုံးမှာ summary တစ်ခု ပြန်ပေးနိုင်ပါတယ်။ ဒါက အလုပ်ကို အပိုင်းလိုက် ခွဲထားတဲ့ generator တွေမှာ အသုံးဝင်ပါတယ်။
def read_batch(rows):
good = 0
for row in rows:
if row.strip():
good += 1
yield row.strip()
return good # becomes the value of yield from
def read_all(batches):
for i, rows in enumerate(batches, start=1):
count = yield from read_batch(rows)
print(f" batch {i}: {count} rows")
print(list(read_all([["a", " ", "b"], ["c"]])))| itertools function | ဘာလုပ်လဲ |
|---|---|
| islice(it, n) | ပထမ n ခုကို lazy ယူ (it[:n] လို) |
| chain(a, b) | Iterable တွေကို တစ်ဆက်တည်း ပတ် |
| groupby(sorted_it, key) | ကပ်လျက် key တူတာတွေ အုပ်စုဖွဲ့ |
| accumulate(it) | Running total (ဒါမှမဟုတ် function) ထုတ် |
| takewhile(pred, it) | pred မှားတာနဲ့ ရပ် |
လက်တွေ့ project တွေမှာ
Real project တွေမှာ ဘယ်လို သုံးလဲ
Data engineering မှာ generator pipeline တွေကို ETL script တွေထဲ တွေ့ရပါတယ် — read_rows(file) → clean(rows) → validate(rows) → batch(rows, 500) → database insert လိုပါ။ Stage တစ်ခုချင်းက သေးပြီး သီးခြား test လုပ်လို့ရကာ file အရွယ်အစား ဘယ်လောက်ကြီးကြီး memory သုံးစွဲမှုက တည်ငြိမ်နေပါတယ်။ islice နဲ့ ပထမ row ဆယ်ကြောင်းပဲ ယူပြီး pipeline တစ်ခုလုံးကို မြန်မြန် debug လုပ်လို့လည်း ရပါတယ်။
send() နဲ့ throw() ကို နေ့စဉ် application code မှာ တိုက်ရိုက် ရေးရတာ နည်းပါတယ်၊ ဒါပေမယ့် ဒီ mechanism တွေက တခြား tool တွေရဲ့ အခြေခံပါ။ contextlib.contextmanager က generator ရဲ့ yield တစ်ခုကို with block ရဲ့ အလယ်အဖြစ် သုံးပြီး with block ထဲမှာ exception တက်ရင် throw() နဲ့ generator ထဲ ပြန်ပို့ပါတယ်။ pytest ရဲ့ yield fixture တွေကလည်း yield မတိုင်ခင်ကို setup၊ yield ပြီးနောက်ကို teardown အဖြစ် သုံးပါတယ်။ Python ရဲ့ async/await ကလည်း သမိုင်းအရ generator ရဲ့ send() mechanism ကနေ ဆင့်ကဲ ဖြစ်လာတာပါ။
အမှားများ
အဖြစ်များတဲ့ အမှားတွေ
1. Prime မလုပ်ဘဲ send() ခေါ်တာ
avg = running_average(); avg.send(10) က "can't send non-None value to a just-started generator" TypeError ပေးပါတယ်။ ပထမဆုံး next(avg) ဒါမှမဟုတ် avg.send(None) ကို ခေါ်ပါ။ အမြဲ မေ့တတ်ရင် generator ကို ဆောက်ပြီး next() ခေါ်ကာ ပြန်ပေးတဲ့ helper function သေးသေးလေး ရေးထားပါ။
2. groupby ကို မစီရသေးတဲ့ data ပေါ် သုံးတာ
groupby က SQL ရဲ့ GROUP BY လို မဟုတ်ပါဘူး၊ ကပ်လျက်ရှိတဲ့ item တွေကိုပဲ ကြည့်ပါတယ်။ ["/a", "/b", "/a"] ကို တိုက်ရိုက်သုံးရင် /a အုပ်စု နှစ်ခု ထွက်ပြီး count တွေ မှားပါတယ်။ အရင် key တူတူနဲ့ sorted() လုပ်ပါ ဒါမှမဟုတ် collections.Counter ကို သုံးပါ။ Group iterator ကိုလည်း နောက် group မသွားခင် list() နဲ့ ယူထားရပါမယ်၊ မဟုတ်ရင် ဗလာ ဖြစ်သွားပါတယ်။
3. Pipeline ထဲက generator ကို stage နှစ်ခုက မျှသုံးတာ
records = parse(LOG) ကို errors(records) နဲ့ count(records) နှစ်ခုလုံးဆီ ပို့ရင် stage တစ်ခုက ယူသွားတဲ့ record ကို နောက်တစ်ခုက မမြင်ရပါဘူး၊ ရလဒ် နှစ်ခုလုံး မစုံပါဘူး။ Stage တစ်ခုစီအတွက် parse(LOG) ကို အသစ် ခေါ်ပါ ဒါမှမဟုတ် itertools.tee ကို သုံးပါ (tee က buffer ထားလို့ memory ကုန်နိုင်တာ သတိထားပါ)။
4. Cleanup ကို finally အပြင်မှာ ရေးတာ
File ပိတ်တဲ့ code ကို while loop ရဲ့ နောက်မှာ ရိုးရိုး ရေးထားရင် caller က loop ကို break နဲ့ ထွက်တာ ဒါမှမဟုတ် close() ခေါ်တာနဲ့ အဲဒီ line ကို ဘယ်တော့မှ မရောက်ပါဘူး။ Generator ထဲက resource တွေကို with statement ဒါမှမဟုတ် try/finally နဲ့ ကာကွယ်ပါ၊ ဒါမှ GeneratorExit တက်တဲ့အခါမှာတောင် ပိတ်ပါမယ်။
Mini challenge
Mini challenge: အသုံးစရိတ် pipeline
နေ့တစ်နေ့ချင်းရဲ့ "name,amount" line list တွေကို generator stage တွေနဲ့ ဖြတ်ပြီး budget 35 မကျော်သေးခင်အထိ running total တွေကို ထုတ်ပါ။ Format မှားတဲ့ line တွေကို ကျော်ပြီး message ပြရပါမယ်။
- all_lines(*days) က yield from နဲ့ day list အားလုံးကို တစ်ဆက်တည်း ထုတ်ရမယ်
- parse_amounts(lines) က (name, float) tuple တွေ yield ပေးပြီး float မဖြစ်တဲ့ line ကို "skipped bad line" နဲ့ ကျော်ရမယ်
- running_totals က itertools.accumulate ကို သုံးရမယ်၊ takewhile နဲ့ 35 အထိပဲ ယူရမယ်
- islice နဲ့ Tuesday ရဲ့ မှန်ကန်တဲ့ item နှစ်ခုကို ယူပြီး print ထုတ်ရမယ်
import itertools
MONDAY = ["coffee,3.5", "lunch,12", "oops", "book,18"]
TUESDAY = ["bus,1.5", "dinner,abc", "snack,4"]
def all_lines(*days):
# TODO: delegate to each day's list
...
def parse_amounts(lines):
# TODO: split each line at the first comma (str.partition)
# TODO: yield (name, float(amount)); on ValueError print " skipped bad line: ..."
...
def running_totals(expenses):
# TODO: a generator expression of amounts, passed to itertools.accumulate
...
# TODO: chain the stages, keep totals <= 35 with takewhile, print them
# TODO: print the first two valid Tuesday items using isliceရလဒ်: Output က ဒီလို ဖြစ်ရပါမယ်: skipped bad line: 'oops' skipped bad line: 'dinner,abc' totals within budget: [3.5, 15.5, 33.5, 35.0] skipped bad line: 'dinner,abc' first two Tuesday items: [('bus', 1.5), ('snack', 4.0)]
အရိပ်အမြွက် ကြည့်ရန်
"oops".partition(",") က ("oops", "", "") ပြန်ပြီး float("") က ValueError တက်လို့ comma မပါတဲ့ line ကိုလည်း except တစ်ခုတည်းနဲ့ ဖမ်းနိုင်ပါတယ်။ takewhile က 35 ကျော်တဲ့ total ကို တွေ့တာနဲ့ ရပ်လို့ နောက်က line တွေကို parse မလုပ်တော့ပါဘူး။
အဖြေ ကြည့်ရန်
import itertools
MONDAY = ["coffee,3.5", "lunch,12", "oops", "book,18"]
TUESDAY = ["bus,1.5", "dinner,abc", "snack,4"]
def all_lines(*days):
for day in days:
yield from day
def parse_amounts(lines):
for line in lines:
name, _, amount = line.partition(",")
try:
yield name, float(amount)
except ValueError:
print(f" skipped bad line: {line!r}")
def running_totals(expenses):
amounts = (amount for _, amount in expenses)
return itertools.accumulate(amounts)
expenses = parse_amounts(all_lines(MONDAY, TUESDAY))
totals = running_totals(expenses)
under_budget = itertools.takewhile(lambda t: t <= 35, totals)
print("totals within budget:", list(under_budget))
first_two = itertools.islice(parse_amounts(all_lines(TUESDAY)), 2)
print("first two Tuesday items:", list(first_two))Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- value = yield x က x ကို ထုတ်ပေးပြီး send() ပို့တဲ့ value ကို လက်ခံပါတယ်၊ ပထမဆုံး next() နဲ့ prime လုပ်ရပါတယ်။
- throw() က ရပ်ထားတဲ့ yield မှာ exception တက်စေပြီး close() က GeneratorExit နဲ့ finally cleanup ကို run စေပါတယ်။
- yield from က sub-generator ဆီ အလုပ်လွှဲပြီး send/throw ကို ဖြတ်ပို့ကာ return value ကိုလည်း ယူပါတယ်။
- Generator stage တွေကို ဆက်ရင် record တစ်ခုချင်း ဖြတ်သွားတဲ့ lazy pipeline ရပြီး itertools က islice, chain, groupby, accumulate, takewhile လို အစိတ်အပိုင်းတွေ ပေးပါတယ်။
Python Documentation — Functional Programming HOWTO — Python Software Foundation