ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
စားသောက်ဆိုင်တစ်ဆိုင်မှာ ဟင်းပွဲ ဆယ်ပွဲကို တစ်ခါတည်း ချက်ပြီး စားပွဲပေါ် အကုန်တင်ထားတာနဲ့ ဧည့်သည်က မှာမှ တစ်ပွဲချင်း ချက်ပေးတာ ကွာပါတယ်။ ပထမနည်းက နေရာအများကြီး ယူပြီး မစားဖြစ်တဲ့ ဟင်းတွေလည်း အလဟဿ ဖြစ်နိုင်ပါတယ်။ ဒုတိယနည်းက လိုတဲ့အချိန်မှ လိုသလောက်ပဲ လုပ်ပါတယ်။
List တစ်ခုက ပထမနည်းလိုပါ — element အားလုံးကို memory ထဲမှာ တစ်ခါတည်း ထားပါတယ်။ Generator ကတော့ ဒုတိယနည်းပါ — "နောက်တစ်ခု ပေးပါ" လို့ တောင်းမှ value တစ်ခု တွက်ပြီး ပေးပါတယ်၊ ပြီးရင် ဘယ်နေရာမှာ ရပ်ခဲ့လဲ မှတ်ထားပြီး နောက်တစ်ကြိမ် တောင်းတဲ့အထိ စောင့်နေပါတယ်။
Problem → Why → Solution
ပြဿနာ: မလိုအပ်ဘဲ အကုန်လုံးကို memory ထဲ ထည့်ထားတာ
Log file ကြီးတစ်ခုထဲက error line တွေကို ရှာချင်တယ် ဆိုပါစို့။ အောက်က function က line သန်းချီကို list တစ်ခုထဲ အရင်စုပြီးမှ return ပြန်ပါတယ်။ Caller က ပထမဆုံး error တစ်ခုပဲ လိုချင်ပေမယ့် file တစ်ခုလုံး ဖတ်ပြီး ပြီးတဲ့အထိ စောင့်ရပါတယ်။ File က RAM ထက် ကြီးရင် program က MemoryError နဲ့ ရပ်သွားနိုင်ပါတယ်။
def error_lines(path):
found = []
with open(path) as f:
for line in f:
if "ERROR" in line:
found.append(line) # every match is kept in memory
return found # nothing reaches the caller until the end
first = error_lines("server.log")[0] # read 5 GB to use one lineဘာကြောင့် ဒါက အလုပ်ပိုတာလဲ
return က function ကို တစ်ကြိမ်တည်း အဆုံးသတ်ပြီး ရလဒ်ကို တစ်ခါတည်း ပေးရလို့ အရာအားလုံးကို အရင်စုထားရပါတယ်။ yield ကတော့ value တစ်ခု ပေးပြီး function ကို ခဏ ရပ်ထားပါတယ်။ append(line) နေရာမှာ yield line လို့ ပြောင်းလိုက်ရင် caller က ပထမ error ကို ချက်ချင်း ရပြီး လိုသလောက်ပဲ ဆက်ဖတ်ပါတယ်။
Core concept: ရပ်လိုက်၊ ဆက်လိုက် လုပ်နိုင်တဲ့ function
Function body ထဲမှာ yield keyword တစ်ခု ပါတာနဲ့ အဲဒါက generator function ဖြစ်သွားပါတယ်။ အရေးကြီးဆုံးအချက်က countdown(3) လို ခေါ်လိုက်ရင် body ထဲက line တစ်ကြောင်းမှ မ run သေးတာပါ။ Python က generator object တစ်ခုကိုပဲ ပြန်ပေးပါတယ် — ဒါက ရပ်ထားတဲ့ function call တစ်ခုလိုပါ၊ local variable တွေနဲ့ ဘယ် line မှာ ရောက်နေလဲဆိုတာကို သိမ်းထားပါတယ်။
next(gen) ခေါ်တဲ့အခါ body က ရပ်ထားတဲ့နေရာကနေ နောက် yield တစ်ခုအထိ run ပါတယ်။ yield n က n ကို caller ဆီ ပေးပြီး အဲဒီနေရာမှာပဲ ရပ်ပါတယ်။ နောက်တစ်ကြိမ် next() ခေါ်ရင် yield ရဲ့ နောက် line ကနေ ဆက်ပြီး n -= 1 လို အပြောင်းအလဲတွေကို မှတ်ထားလို့ ယခင် ရပ်ခဲ့တဲ့ state ကနေ ဆက်တွက်ပါတယ်။ Body ရဲ့ အဆုံး ဒါမှမဟုတ် return statement ကို ရောက်သွားရင် next() က StopIteration exception တက်ပြီး "value ကုန်ပြီ" လို့ အချက်ပြပါတယ်။
for loop က ဒီ protocol ကို အလိုအလျောက် ကိုင်ပေးပါတယ်။ for value in gen: က နောက်ကွယ်မှာ next() ကို ထပ်ခါထပ်ခါ ခေါ်ပြီး StopIteration ကို ဖမ်းကာ loop ကို တိတ်တဆိတ် ရပ်ပေးပါတယ်။ list(), sum(), max() လို function တွေကလည်း iterable တွေကို ဒီနည်းနဲ့ပဲ စားသုံးပါတယ်။ Generator တွေက iterator တွေ ဖြစ်လို့ တစ်ကြိမ်ပဲ သုံးလို့ရပါတယ် — ကုန်သွားပြီးရင် ပြန်စချင်ရင် generator function ကို ထပ်ခေါ်ပြီး object အသစ် ယူရပါတယ်။
ဒီ lazy evaluation ကြောင့် generator တစ်ခုက memory ထဲမှာ value တစ်ခုစာလောက်ပဲ ထားပါတယ်၊ sequence ဘယ်လောက်ရှည်ရှည် အရွယ်အစား သိပ်မပြောင်းပါဘူး။ ဒါကြောင့် while True ပါတဲ့ အဆုံးမရှိတဲ့ generator ကိုတောင် ရေးလို့ရပါတယ်၊ caller က လိုသလောက်ပဲ ယူတာမို့ပါ။ Generator expression က ဒါကို တိုတိုရေးတဲ့ နည်းပါ — list comprehension ရဲ့ [ ] နေရာမှာ ( ) သုံးလိုက်ရင် (x * x for x in data) က list မဆောက်ဘဲ generator တစ်ခု ပြန်ပေးပါတယ်။
- ခေါ်လိုက်ရင် ရပ်ထားတဲ့ object ရ
- next() က နောက် yield အထိ run
- yield က value ပေးပြီး ရပ်
- Body ဆုံးရင် StopIteration
Local variable တွေက yield တွေကြားမှာ ဆက်ရှင်နေပါတယ်၊ ဒါကြောင့် ရပ်ခဲ့တဲ့ နေရာကနေ ဆက်နိုင်တာပါ။
အထွေထွေ ပုံစံ
def produce(source):
for item in source:
yield transform(item) # hand out one value, then pause
gen = produce(data) # nothing has run yet
first = next(gen) # run up to the first yield
for value in gen: # keep calling next() until StopIteration
use(value)
lazy = (expression for item in iterable if condition)yield ပါတဲ့ function ကို ခေါ်ရင် generator object ရပါတယ်။ next() နဲ့ value တစ်ခုချင်း ယူနိုင်ပြီး for loop က ကျန်တာအားလုံးကို ယူပါတယ်။ နောက်ဆုံး line က လက်သည်းကွင်း သုံးထားတဲ့ generator expression ပါ။
Example: generator ဘယ်အချိန် run လဲ ခြေရာခံကြည့်ခြင်း
countdown generator ထဲမှာ အစနဲ့ အဆုံးမှာ print line တွေ ထည့်ထားလို့ body က ဘယ်အချိန် တကယ် run လဲ မြင်ရပါမယ်။ Output ထဲက indent လုပ်ထားတဲ့ "(...)" line တွေ ဘယ်နေရာမှာ ပေါ်လဲ သေချာကြည့်ပါ — ဒါက lazy evaluation ကို ပြတဲ့ အထောက်အထားပါ။
def countdown(n):
print(f" (countdown starts at {n})")
while n > 0:
yield n
n -= 1
print(" (countdown finished)")
gen = countdown(3)
print("1. created:", type(gen).__name__)
print("2. first next():", next(gen))
print("3. second next():", next(gen))
print("4. the rest:", list(gen))
print("5. used up:", list(gen))
try:
next(gen)
except StopIteration:
print("6. next() on a finished generator raises StopIteration")
def naturals():
n = 1
while True:
yield n
n += 1
numbers = naturals()
print("7. first five:", [next(numbers) for _ in range(5)])
print("8. it remembers:", next(numbers))
squares = (x * x for x in range(1, 6))
print("9. sum of squares:", sum(squares))Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Line 9-10
gen = countdown(3)countdown(3) ကို ခေါ်ပေမယ့် "(countdown starts at 3)" မပေါ်သေးပါဘူး။ Output ရဲ့ ပထမ line က "1. created: generator" ဖြစ်ပြီး body က လုံးဝ မ run သေးကြောင်း သက်သေပြပါတယ်။
- Line 11
print("2. first next():", next(gen))ပထမ next() မှာမှ body စ run ပြီး start line ကို print ထုတ်ကာ yield n မှာ 3 ကို ပေးပြီး ရပ်ပါတယ်။ ဒါကြောင့် "(countdown starts at 3)" က "2." line ရဲ့ အပေါ်မှာ ပေါ်တာပါ။
- Line 13
print("4. the rest:", list(gen))list() က StopIteration တက်တဲ့အထိ next() ကို ဆက်ခေါ်ပါတယ်။ 1 ကို ယူပြီးနောက် while loop ပြီးသွားလို့ "(countdown finished)" print ထွက်ပြီး function ဆုံးပါတယ်။ ကျန်တာ [1] တစ်ခုပဲ ရှိတာက 3 နဲ့ 2 ကို အရင်ယူပြီးသား ဖြစ်လို့ပါ။
- Line 14-19
print("5. used up:", list(gen))ကုန်သွားပြီးသား generator ကို list() ထပ်လုပ်ရင် error မတက်ဘဲ [] ပဲ ရပါတယ်။ next() ကို တိုက်ရိုက် ခေါ်ရင်တော့ StopIteration တက်လို့ try/except နဲ့ ဖမ်းပြထားပါတယ်။
- Line 22-31
while True:naturals() က အဆုံးမရှိ ဆက်ထုတ်ပေမယ့် caller က ငါးခုပဲ တောင်းလို့ program မရပ်မနား မဖြစ်ပါဘူး။ နောက် next() က 6 ပေးတာက n ကို yield တွေကြားမှာ မှတ်ထားလို့ပါ။
- Line 33-34
squares = (x * x for x in range(1, 6))လက်သည်းကွင်းကြောင့် list မဟုတ်ဘဲ generator expression ဖြစ်ပါတယ်။ sum() က value တွေကို တစ်ခုချင်း ယူပေါင်းလို့ 1 + 4 + 9 + 16 + 25 = 55 ရပါတယ်။
1. created: generator
(countdown starts at 3)
2. first next(): 3
3. second next(): 2
(countdown finished)
4. the rest: [1]
5. used up: []
6. next() on a finished generator raises StopIteration
7. first five: [1, 2, 3, 4, 5]
8. it remembers: 6
9. sum of squares: 55for loop ရဲ့ နောက်ကွယ်: iter() နဲ့ next()
Python ရဲ့ iteration protocol မှာ အပိုင်းနှစ်ခု ရှိပါတယ်။ Iterable (list, string, dict လို) ဆိုတာ iter() ကို ခေါ်ရင် iterator တစ်ခု ပြန်ပေးနိုင်တဲ့ object ပါ။ Iterator ဆိုတာ next() ကို ခေါ်ရင် နောက် value ပေးပြီး ကုန်ရင် StopIteration တက်တဲ့ object ပါ။ List က iterable ဖြစ်ပေမယ့် iterator မဟုတ်လို့ for loop နှစ်ကြိမ် ပတ်နိုင်ပါတယ်၊ loop တိုင်းက iterator အသစ် ယူလို့ပါ။ Generator ကတော့ iter(gen) is gen ဖြစ်တဲ့ iterator ကိုယ်တိုင်မို့ တစ်ကြိမ်ပဲ ပတ်နိုင်ပါတယ်။
| List | Generator | |
|---|---|---|
| Value တွေ ဘယ်အချိန် တွက်လဲ | ဆောက်တဲ့အချိန် အကုန် | next() တောင်းမှ တစ်ခုချင်း |
| Memory | Element အရေအတွက်နဲ့ အချိုးကျ | အရွယ်အစား သေးသေး၊ ပုံသေနီးပါး |
| ထပ်ပတ်လို့ ရလား | ရပါတယ် | မရပါ၊ အသစ် ထပ်ဆောက်ရ |
| len(), [0] indexing | ရပါတယ် | TypeError တက်ပါတယ် |
import sys
as_list = [n * 2 for n in range(1_000_000)]
as_gen = (n * 2 for n in range(1_000_000))
# Exact byte counts depend on the Python version and platform
print("list bytes:", sys.getsizeof(as_list)) # millions of bytes
print("generator bytes:", sys.getsizeof(as_gen)) # a few hundred bytes
print(sum(as_gen) == sum(as_list)) # same values: Trueလက်တွေ့ project တွေမှာ
Real project တွေမှာ ဘယ်လို သုံးလဲ
Python ရဲ့ file object တွေ ကိုယ်တိုင်က lazy iterator တွေပါ — for line in open(path): က file တစ်ခုလုံးကို memory ထဲ မတင်ဘဲ line တစ်ကြောင်းချင်း ဖတ်ပါတယ်။ ဒါကို generator နဲ့ တွဲလိုက်ရင် gigabyte အရွယ် log, CSV export နဲ့ data dump တွေကို laptop သေးသေးလေးပေါ်မှာတောင် ဖတ်လို့ ရပါတယ်။ range(), dict.items(), zip(), map() တို့ကလည်း list မဆောက်ဘဲ value တွေကို လိုမှ ထုတ်ပေးပါတယ်။
API ကနေ page တွေ ခွဲပြီး data ယူရတဲ့အခါ generator က page တစ်ခုချင်း request လုပ်ပြီး item တွေကို တစ်ခုချင်း yield ပေးပါတယ်၊ caller ကတော့ page ဆိုတာ ရှိမှန်းတောင် မသိဘဲ ရိုးရိုး for loop ပဲ ရေးရပါတယ်။ Django ရဲ့ QuerySet.iterator() လို ORM method တွေက database row တွေကို batch လိုက် ဖတ်ပေးပြီး sum(order.total for order in orders) လို generator expression တွေက aggregate တွက်တဲ့အခါ ကြားခံ list မဆောက်ပါဘူး။ ဒါပေမယ့် data ကို နှစ်ကြိမ် ပတ်ဖို့ ဒါမှမဟုတ် len() လိုရင်တော့ list က ပိုသင့်တော်ပါတယ်။
အမှားများ
အဖြစ်များတဲ့ အမှားတွေ
1. Generator ကို နှစ်ကြိမ် ပတ်တာ
scores = (s for s in data) ရေးပြီး max(scores) နဲ့ min(scores) ကို ဆက်တိုက် ခေါ်ရင် ပထမတစ်ခုက generator ကို ကုန်အောင် စားသွားလို့ min() က "min() iterable argument is empty" ValueError တက်ပါတယ်။ for loop ဆိုရင်တော့ ဒုတိယ loop က error မတက်ဘဲ ဘာမှ မလုပ်ဘဲ ကျော်သွားလို့ ပိုရှာရခက်ပါတယ်။ နှစ်ကြိမ် လိုရင် list() နဲ့ သိမ်းပါ။
2. Generator function ကို ခေါ်ရုံနဲ့ run ပြီလို့ ထင်တာ
save_all(rows) ထဲမှာ yield ပါနေရင် save_all(rows) လို့ ခေါ်ရုံနဲ့ row တစ်ခုမှ save မဖြစ်ပါဘူး၊ generator object ပဲ ရပြီး ပစ်ချလိုက်တာပါ။ Side effect အတွက် ရေးထားတဲ့ function ထဲမှာ yield မထည့်ပါနဲ့၊ ဒါမှမဟုတ် for loop ဒါမှမဟုတ် list() နဲ့ တကယ် iterate လုပ်ပါ။
3. List လို indexing နဲ့ len() သုံးတာ
gen[0] က "'generator' object is not subscriptable" TypeError ပေးပြီး len(gen) က "object of type 'generator' has no len()" ပေးပါတယ်။ ပထမ value တစ်ခုပဲ လိုရင် next(gen) ကို သုံးပါ၊ ကုန်နေနိုင်ရင် next(gen, None) လို default တစ်ခု ပေးပါ။
4. အဆုံးမရှိတဲ့ generator ကို list() လုပ်တာ
list(naturals()) က StopIteration ဘယ်တော့မှ မတက်လို့ memory ကုန်တဲ့အထိ ဆက် run ပါတယ်။ အဆုံးမရှိတဲ့ generator ကနေ လိုသလောက်ပဲ ယူဖို့ loop ထဲမှာ break သုံးပါ ဒါမှမဟုတ် next() ကို အကြိမ်အရေအတွက် သတ်မှတ်ပြီး ခေါ်ပါ။
Mini challenge
Mini challenge: item တွေကို batch လိုက် ခွဲတဲ့ generator
Iterable တစ်ခုကို အရွယ် size ရှိတဲ့ list batch တွေအဖြစ် တစ်ခုချင်း yield ပေးတဲ့ chunked(items, size) generator ကို ရေးပါ။ Database ထဲ row တွေကို အုပ်လိုက် ထည့်တာ၊ API ကို batch request ပို့တာတွေမှာ သုံးတဲ့ ပုံစံပါ။
- size က 1 အောက် ဖြစ်ရင် ValueError တက်ရမယ်
- နောက်ဆုံး batch က size ထက် သေးနိုင်ပေမယ့် ကျန်ခဲ့လို့ မရဘူး
- Item အားလုံးကို list တစ်ခုထဲ ကြိုမစုရ — batch တစ်ခုစာပဲ ကိုင်ထားရမယ်
- next() နဲ့ ပထမ batch ယူပြီး ကျန်တဲ့ batch အရွယ်တွေကို print ထုတ်ရမယ်
def chunked(items, size):
# TODO: reject a size below 1 with ValueError
# TODO: fill a batch list item by item
# TODO: yield the batch when it is full, then start a new one
# TODO: after the loop, yield a final partial batch if one is left
...
# TODO: print list(chunked(range(7), 3)), list(chunked("abcd", 2)), list(chunked([], 3))
# TODO: batches = chunked(range(1, 11), 4); print next(batches), then remaining sizes
# TODO: print the total of the even numbers 1..10 with a generator expressionရလဒ်: Output က ဒီလို ဖြစ်ရပါမယ်: [[0, 1, 2], [3, 4, 5], [6]] [['a', 'b'], ['c', 'd']] [] first batch: [1, 2, 3, 4] batch sizes left: [4, 2] total of evens: 30
အရိပ်အမြွက် ကြည့်ရန်
batch = [] နဲ့ စပြီး item တိုင်းကို append လုပ်ပါ။ len(batch) == size ဖြစ်ရင် yield batch ပြီးနောက် batch = [] လို့ list အသစ် ပြန်စပါ (ဟောင်းကို clear() မလုပ်ပါနဲ့၊ yield ပေးပြီးသား list ပါ ပြောင်းသွားမှာမို့ပါ)။
အဖြေ ကြည့်ရန်
def chunked(items, size):
if size < 1:
raise ValueError("size must be at least 1")
batch = []
for item in items:
batch.append(item)
if len(batch) == size:
yield batch
batch = []
if batch:
yield batch
print(list(chunked(range(7), 3)))
print(list(chunked("abcd", 2)))
print(list(chunked([], 3)))
batches = chunked(range(1, 11), 4)
print("first batch:", next(batches))
print("batch sizes left:", [len(b) for b in batches])
print("total of evens:", sum(n for n in range(1, 11) if n % 2 == 0))Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- yield ပါတဲ့ function ကို ခေါ်ရင် body မ run ဘဲ generator object ပဲ ရပါတယ်။
- next() တစ်ခါစီက နောက် yield အထိ run ပြီး local state ကို ရပ်ထားတဲ့နေရာမှာ မှတ်ထားပါတယ်။
- Body ဆုံးရင် StopIteration တက်ပြီး for loop က အဲဒါကို အလိုအလျောက် ကိုင်ပေးပါတယ်၊ generator က တစ်ကြိမ်ပဲ သုံးလို့ရပါတယ်။
- (expr for x in data) generator expression က list မဆောက်ဘဲ data ကြီးကြီးနဲ့ အဆုံးမရှိ sequence တွေကို memory သက်သာစွာ ကိုင်ပေးပါတယ်။
Python Documentation — Functional Programming HOWTO — Python Software Foundation