ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
သူငယ်ချင်းကို "ဗီရိုထဲက အကျီတစ်ထည် ယူခဲ့ပေး" လို့ စာရေးထားခဲ့တယ် ဆိုပါစို့။ စာက အကျီကို ဓာတ်ပုံရိုက်ထားတာ မဟုတ်ဘဲ "ဗီရိုထဲက" လို့ နေရာကိုပဲ ညွှန်းထားတာပါ။ သူငယ်ချင်း စာဖတ်ချိန်မှာ ဗီရိုထဲ ဘာရှိနေလဲ ဆိုတာပေါ် မူတည်ပြီး ရလာမှာပါ — သင်ထွက်သွားပြီးနောက် တစ်ယောက်ယောက်က အကျီ လဲထားရင် အဲဒီ အသစ်ကို ယူလာမှာပါ။
Lambda ထဲက အပြင် variable တွေကလည်း အဲဒီ စာလိုပါပဲ။ lambda x: x + i က i ရဲ့ value ကို ဆောက်တဲ့အချိန်မှာ မှတ်မထားပါဘူး၊ ခေါ်တဲ့အချိန်ရောက်မှ i ကို သွားကြည့်ပါတယ်။ ဒါကို နားလည်ရင် lambda တွေကို ဘေးကင်းကင်း သုံးနိုင်ပြီး partial နဲ့ operator လို ကိရိယာတွေက ဘာကြောင့် အသုံးဝင်လဲ သိလာပါမယ်။
Problem → Why → Solution
ပြဿနာ: button သုံးခုလုံးက နောက်ဆုံး နာမည်ကိုပဲ ပြနေတာ
Menu item တစ်ခုစီအတွက် click handler တစ်ခုစီ ဆောက်ဖို့ loop ထဲမှာ lambda တွေ ဖန်တီးတယ် ဆိုပါစို့။ Code က မှန်သလို ထင်ရပြီး error လည်း မတက်ပါဘူး။ ဒါပေမယ့် ဘယ် button ကို နှိပ်နှိပ် "Save" မဟုတ်ဘဲ "Quit" ပဲ ထွက်ပါတယ်။ Test တစ်ခုမှာ handler တစ်ခုပဲ စစ်ရင် ဒီ bug ကို လုံးဝ မမြင်ရနိုင်ပါဘူး။
labels = ["Save", "Open", "Quit"]
handlers = []
for label in labels:
handlers.append(lambda: f"clicked {label}")
print(handlers[0]()) # clicked Quit (expected: clicked Save)
print(handlers[1]()) # clicked Quit (expected: clicked Open)ဘာကြောင့် Quit ချည်းပဲ ထွက်တာလဲ
Lambda သုံးခုလုံးက label ဆိုတဲ့ variable တစ်ခုတည်းကို နာမည်နဲ့ ညွှန်းထားပါတယ်။ Handler တွေကို ခေါ်တဲ့အချိန်မှာ loop က ပြီးသွားပြီး label ရဲ့ နောက်ဆုံး value က "Quit" ဖြစ်နေလို့ အားလုံးက အဲဒါကိုပဲ ဖတ်ကြပါတယ်။ ဒါကို late binding လို့ ခေါ်ပြီး ပြင်ဖို့ ဆောက်တဲ့အချိန်မှာ value ကို ချည်ထားပေးရပါမယ်။
Core concept: lambda က value မဟုတ်ဘဲ variable ကို မှတ်တာ
Function တစ်ခုထဲမှာ lambda ကို ဆောက်ပြီး အပြင် function ရဲ့ variable ကို သုံးရင် closure ဖြစ်လာပါတယ်။ make_multiplier(3) က lambda x: x * factor ကို return ပြန်ပြီး make_multiplier ပြီးသွားတဲ့နောက်မှာတောင် lambda က factor ကို ဆက်ဖတ်နိုင်ပါတယ်။ Python က အဲဒီ variable ကို cell လို့ ခေါ်တဲ့ သေတ္တာလေးထဲ ထည့်ပြီး lambda က value ကို မဟုတ်ဘဲ သေတ္တာကို ကိုင်ထားပါတယ်။ make_multiplier ကို ခေါ်တိုင်း scope အသစ်နဲ့ cell အသစ် ရလို့ triple နဲ့ double က factor ကို မျှမသုံးပါဘူး။
ပြဿနာက loop ထဲမှာ ဖြစ်ပါတယ်။ for loop တစ်ခုက scope အသစ် မဆောက်ပါဘူး၊ i ဆိုတဲ့ variable တစ်ခုတည်းကို လှည့်တိုင်း value အသစ် ထည့်ပြီး ပြန်သုံးပါတယ်။ ဒါကြောင့် [lambda x: x + i for i in range(3)] ထဲက lambda သုံးခုလုံးက cell တစ်ခုတည်းကို ကိုင်ထားပြီး ခေါ်တဲ့အချိန်မှာ i က 2 ဖြစ်နေလို့ အားလုံး x + 2 ကို တွက်ပါတယ်။ List comprehension မှာ ကိုယ်ပိုင် scope ရှိပေမယ့် iteration အားလုံးက အဲဒီ scope တစ်ခုတည်းကို မျှသုံးလို့ ရလဒ်က အတူတူပါပဲ။
ပြင်နည်း သုံးမျိုး ရှိပါတယ်။ ပထမ — lambda x, i=i: x + i လို default argument သုံးပါ၊ default value က lambda ဆောက်တဲ့အချိန်မှာ တစ်ကြိမ်တည်း တွက်လို့ အဲဒီ အချိန်က value ကို သိမ်းထားပါတယ်။ ဒုတိယ — make_adder(i) လို factory function ခေါ်ပြီး ခေါ်တိုင်း scope အသစ် ရအောင် လုပ်ပါ။ တတိယ — functools.partial(add, i) ကို သုံးပါ၊ partial က argument တွေကို ဆောက်တဲ့အချိန်မှာပဲ သိမ်းပါတယ်။
functools.partial(func, *args, **kwargs) က func ကို argument အချို့ ကြိုဖြည့်ထားတဲ့ callable အသစ်တစ်ခု ပြန်ပေးပါတယ်။ partial(int, base=2) က binary string ကို parse လုပ်တဲ့ function ဖြစ်လာပါတယ်။ operator module ကတော့ Python operator တွေကို function အဖြစ် ပေးပါတယ် — operator.mul က lambda a, b: a * b နဲ့ အလုပ်တူပြီး itemgetter(2, 0) က index 2 နဲ့ 0 ကို tuple အဖြစ် ထုတ်ယူတဲ့ function ကို ဆောက်ပေးပါတယ်။ ဒါတွေက နာမည်နဲ့ ဖော်ပြထားလို့ ဖတ်ရလွယ်ပြီး repr ထဲမှာ ဘာလုပ်လဲ မြင်ရကာ late-binding ပြဿနာလည်း မရှိပါဘူး။
- Lambda ဆောက်ရင် cell ကို ကိုင်ထား
- Loop က cell ထဲ value လဲ
- ခေါ်မှ cell ထဲ ကြည့်
- i=i ဒါမှမဟုတ် partial က value ချည်
Default argument နဲ့ partial က ဆောက်တဲ့အချိန်မှာ တွက်ပြီး lambda body ကတော့ ခေါ်တဲ့အချိန်မှာ တွက်ပါတယ်။
အထွေထွေ ပုံစံ
funcs = [lambda x, v=v: op(x, v) for v in values] # bind v now
from functools import partial, reduce
specialised = partial(func, fixed_arg, keyword=fixed_value)
import operator
key = operator.itemgetter("field") # lambda item: item["field"]
total = reduce(operator.add, items, start)
compose = lambda *fs: reduce(lambda f, g: lambda x: g(f(x)), fs)ပထမ line က loop ထဲမှာ value ကို default argument နဲ့ ချည်တာပါ။ partial က argument ကြိုဖြည့်ပြီး operator function တွေက lambda တိုတိုလေးတွေကို အစားထိုးပါတယ်။ နောက်ဆုံး line က function တွေကို ဘယ်ကနေ ညာ ဆင့်ခေါ်တဲ့ compose ပုံစံပါ။
Example: closure, late binding, partial, operator နဲ့ compose
အပိုင်း 2 နဲ့ 3 က lambda တွေ ဆောက်ပုံ တစ်ခုတည်းကွာပြီး ရလဒ် လုံးဝ ကွာသွားတာကို ကြည့်ပါ။ အပိုင်း 5 နဲ့ 6 က lambda တွေကို operator function တွေနဲ့ အစားထိုးထားပြီး အပိုင်း 7 က function သုံးခုကို pipeline တစ်ခုတည်း ဖြစ်အောင် ပေါင်းထားပါတယ်။
import operator
from functools import partial, reduce
# 1. A lambda returned from a function closes over that call's variables
def make_multiplier(factor):
return lambda x: x * factor
triple = make_multiplier(3)
print("1. closure:", triple(7))
# 2. Late binding: every lambda reads i when it RUNS, after the loop ended
adders = [lambda x: x + i for i in range(3)]
print("2. late binding:", [add(10) for add in adders])
# 3. Fix: a default argument is evaluated once, when each lambda is created
adders = [lambda x, i=i: x + i for i in range(3)]
print("3. default-arg fix:", [add(10) for add in adders])
# 4. functools.partial freezes some arguments of an existing function
parse_binary = partial(int, base=2)
print("4. partial:", parse_binary("1011"), parse_binary("111"))
# 5. operator functions replace one-line lambdas
rows = [("Sai", 25, 88), ("Aye", 20, 95), ("Mya", 30, 88)]
print("5. itemgetter:", sorted(rows, key=operator.itemgetter(2, 0)))
print("6. reduce + mul:", reduce(operator.mul, [1, 2, 3, 4], 1))
# 7. Composition: chain small functions into one, left to right
def compose(*funcs):
return reduce(lambda f, g: lambda x: g(f(x)), funcs, lambda x: x)
slugify = compose(str.strip, str.lower, operator.methodcaller("replace", " ", "-"))
print("7. compose:", slugify(" Learn Python Fast "))Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Line 6-10
return lambda x: x * factormake_multiplier(3) ကို ခေါ်တိုင်း factor = 3 ရှိတဲ့ scope အသစ် ရပြီး lambda က အဲဒီ scope ရဲ့ cell ကို ကိုင်ထားပါတယ်။ ဒီ cell ကို ဘယ်သူမှ ထပ်မပြောင်းလို့ triple(7) က 21 ကို မှန်မှန်ကန်ကန် ရပါတယ်။
- Line 13-14
adders = [lambda x: x + i for i in range(3)]Lambda သုံးခုလုံးက comprehension ရဲ့ i တစ်ခုတည်းကို မျှကိုင်ထားပါတယ်။ add(10) ခေါ်တဲ့အချိန်မှာ i က နောက်ဆုံး value 2 ဖြစ်နေလို့ [12, 12, 12] ရပါတယ်၊ [10, 11, 12] မဟုတ်ပါဘူး။
- Line 17-18
adders = [lambda x, i=i: x + i for i in range(3)]i=i ရဲ့ ညာဘက် i ကို lambda ဆောက်တဲ့ အချိန်မှာ တွက်ပြီး lambda ကိုယ်ပိုင် parameter i ရဲ့ default အဖြစ် သိမ်းပါတယ်။ ဒါကြောင့် lambda တစ်ခုစီက 0, 1, 2 ကို သီးခြားစီ မှတ်ထားပါတယ်။
- Line 21-22
parse_binary = partial(int, base=2)partial က int ကို base=2 ကြိုဖြည့်ထားတဲ့ callable ပြန်ပေးလို့ parse_binary("1011") က int("1011", base=2) = 11 ဖြစ်ပါတယ်။ def ဒါမှမဟုတ် lambda အသစ် ရေးစရာ မလိုပါဘူး။
- Line 26
sorted(rows, key=operator.itemgetter(2, 0))itemgetter(2, 0) က row တစ်ခုချင်းကနေ (score, name) tuple ကို ထုတ်ပေးပြီး lambda r: (r[2], r[0]) နဲ့ အလုပ်တူပါတယ်။ Score 88 တူတဲ့ Mya နဲ့ Sai ကို နာမည်နဲ့ စီလို့ Mya က အရင်လာပါတယ်။
- Line 31-35
return reduce(lambda f, g: lambda x: g(f(x)), funcs, lambda x: x)reduce က identity function ကနေ စပြီး function တစ်ခုချင်းကို ဆင့်ပေါင်းပါတယ်၊ ရလဒ်က strip → lower → replace ကို အစဉ်လိုက် run တဲ့ function တစ်ခုပါ။ ဒီ lambda တွေမှာ late binding ပြဿနာ မရှိပါဘူး — reduce က အပြင် lambda ကို ခေါ်တိုင်း f နဲ့ g အတွက် scope အသစ် ရလို့ပါ။
1. closure: 21
2. late binding: [12, 12, 12]
3. default-arg fix: [10, 11, 12]
4. partial: 11 7
5. itemgetter: [('Mya', 30, 88), ('Sai', 25, 88), ('Aye', 20, 95)]
6. reduce + mul: 24
7. compose: learn-python-fastoperator module ရဲ့ အသုံးများတဲ့ function တွေ
| operator function | ညီမျှတဲ့ lambda |
|---|---|
| itemgetter("name") | lambda d: d["name"] |
| itemgetter(1, 0) | lambda t: (t[1], t[0]) |
| attrgetter("owner.city") | lambda o: o.owner.city |
| methodcaller("split", ",") | lambda s: s.split(",") |
| add, mul, truediv | lambda a, b: a + b (စသဖြင့်) |
attrgetter က dotted path ကိုပါ လက်ခံလို့ object ထဲက object ရဲ့ attribute ကိုလည်း ဖတ်နိုင်ပါတယ်။ ဒီ function တွေက C နဲ့ ရေးထားလို့ sort လုပ်တဲ့ item သန်းချီရှိရင် lambda ထက် အနည်းငယ် မြန်လေ့ရှိပေမယ့် အဓိက အကျိုးက ဖတ်ရလွယ်တာပါ။ ပိုမြန်မမြန် သိချင်ရင် ကိုယ့် data နဲ့ timeit နဲ့ တိုင်းကြည့်ပါ။
from dataclasses import dataclass
from operator import attrgetter, methodcaller
@dataclass
class Owner:
city: str
@dataclass
class Shop:
name: str
owner: Owner
shops = [Shop("Tea", Owner("Yangon")), Shop("Books", Owner("Bago"))]
print([s.name for s in sorted(shops, key=attrgetter("owner.city"))])
print(list(map(methodcaller("split", ","), ["a,b", "c"])))လက်တွေ့ project တွေမှာ
Real project တွေမှာ ဘယ်လို သုံးလဲ
Late-binding bug က GUI နဲ့ event code မှာ အဖြစ်အများဆုံးပါ။ Tkinter မှာ for name in files: Button(..., command=lambda: open_file(name)) လို ရေးရင် button အားလုံးက နောက်ဆုံး file ကိုပဲ ဖွင့်ပါတယ်။ Web scraper, retry scheduler နဲ့ test parametrization ထဲမှာ loop နဲ့ callback ဆောက်တဲ့ နေရာတိုင်းမှာ ဒီပြဿနာ ပေါ်နိုင်ပါတယ်။ command=partial(open_file, name) လို့ ရေးတာက ပြင်ဆင်ချက် အရှင်းဆုံး ဖြစ်လေ့ ရှိပါတယ်။
partial ကို configuration ကြိုဖြည့်ဖို့ နေရာအများကြီးမှာ သုံးပါတယ် — json.dumps ကို partial(json.dumps, indent=2, ensure_ascii=False) နဲ့ ထုပ်ထားတာ၊ executor.map ဆီ argument အပို ပါတဲ့ worker function ပို့တာ၊ callback signature ကိုက်အောင် လုပ်တာမျိုးပါ။ operator.itemgetter နဲ့ attrgetter က report ထုတ်တဲ့ code နဲ့ ORM result စီတဲ့ code တွေမှာ တွေ့ရပြီး compose ပုံစံက text cleaning pipeline နဲ့ data validation step တွေကို function သေးသေးလေးတွေနဲ့ ပေါင်းဆောက်ရာမှာ အသုံးဝင်ပါတယ်။ Function အသေးလေးတွေကို သီးခြားစီ test လုပ်လို့ ရတာကလည်း အကျိုးကျေးဇူး တစ်ခုပါ။
အမှားများ
အဖြစ်များတဲ့ အမှားတွေ
1. Loop variable ကို lambda ထဲ တိုက်ရိုက်သုံးတာ
[lambda: n * n for n in range(3)] ထဲက function တွေ အားလုံး 4 ပြန်ပါတယ်။ Error မတက်လို့ နောက်ဆုံး item တစ်ခုပဲ စစ်တဲ့ test က pass ဖြစ်နိုင်ပါတယ်။ Loop ထဲမှာ callback ဆောက်တိုင်း value ကို n=n default, partial ဒါမှမဟုတ် factory function နဲ့ ချည်ပါ။
2. Default-argument fix ကို caller က ထပ်ဖုံးတာ
lambda x, i=i: x + i မှာ i က parameter တစ်ခု ဖြစ်သွားလို့ caller က f(10, 99) လို ခေါ်မိရင် ချည်ထားတဲ့ value ကို ဖုံးသွားပါတယ်။ API တစ်ခုအဖြစ် ထုတ်ပေးမယ့် callback ဆိုရင် partial ဒါမှမဟုတ် factory function က signature ကို ပိုသန့်ရှင်းစေပါတယ်။
3. partial ကို positional argument နေရာ မှားပေးတာ
partial က positional argument တွေကို ဘယ်ဘက်ကနေ ဖြည့်ပါတယ်။ apply_discount(price, rate) ရဲ့ rate ကို ချည်ချင်လို့ partial(apply_discount, 0.2) လို့ ရေးရင် 0.2 က price ဖြစ်သွားပြီး ရလဒ်မှားပါတယ်။ ဘယ်ဘက်ဆုံးမဟုတ်တဲ့ argument ကို ချည်ချင်ရင် partial(apply_discount, rate=0.2) လို keyword နဲ့ ပေးပါ။
4. reduce ကို start value မပါဘဲ သုံးတာ
reduce(operator.add, []) က "reduce() of empty iterable with no initial value" TypeError ပေးပါတယ်။ Data ဗလာ ဖြစ်နိုင်ရင် reduce(operator.add, items, 0) လို တတိယ argument ပေးပါ။ ပေါင်းတာ၊ မြှောက်တာလို ရိုးရိုးအလုပ်တွေအတွက် sum() နဲ့ math.prod() က ပိုရှင်းပါတယ်။
Mini challenge
Mini challenge: discount နဲ့ order tool များ
Online shop တစ်ခုအတွက် partial, operator နဲ့ compose ကို သုံးပြီး lambda အနည်းဆုံးနဲ့ tool လေးတွေ ဆောက်ပါ။ Loop ထဲမှာ discount function တွေ ဆောက်တဲ့အခါ late binding ကို ရှောင်ရပါမယ်။
- partial နဲ့ 10%, 20%, 30% discount function သုံးခုကို loop တစ်ခုထဲမှာ ဆောက်ရမယ်
- operator.itemgetter နဲ့ order တွေကို total ကြီးရာကနေ စီပြီး total တူရင် id ကြီးတာ အရင်လာရမယ်
- map() နဲ့ itemgetter သုံးပြီး customer နာမည်တွေ ထုတ်ရမယ်
- compose နဲ့ 20% discount → 5% tax → ဒသမ နှစ်နေရာ round ကို pipeline တစ်ခုတည်း ဖြစ်အောင် ပေါင်းရမယ်
import operator
from functools import partial, reduce
def apply_discount(price, rate):
return round(price * (1 - rate), 2)
def compose(*funcs):
# TODO: chain funcs left to right with reduce (start from an identity function)
...
discounts = ... # TODO: one partial per rate in (0.1, 0.2, 0.3), bound by keyword
# TODO: print each discount applied to 50
orders = [
{"id": 3, "customer": "Mya", "total": 120.0},
{"id": 1, "customer": "Aye", "total": 75.5},
{"id": 2, "customer": "Sai", "total": 120.0},
]
# TODO: sort with itemgetter("total", "id") in reverse, print the ids
# TODO: print the customer names using map() and itemgetter
# TODO: build final_price with compose and partial, print final_price(50)ရလဒ်: Output က ဒီလို ဖြစ်ရပါမယ်: discounts on 50: [45.0, 40.0, 35.0] ranked ids: [3, 2, 1] customers: ['Mya', 'Aye', 'Sai'] final price for 50: 42.0
အရိပ်အမြွက် ကြည့်ရန်
Tax အတွက် partial(operator.mul, 1.05) က x ကို 1.05 နဲ့ မြှောက်တဲ့ function ဖြစ်ပါတယ်။ round ကို partial(round, ndigits=2) နဲ့ ထုပ်လို့ ရပါတယ်။ Identity function က lambda x: x ပါ။
အဖြေ ကြည့်ရန်
import operator
from functools import partial, reduce
def apply_discount(price, rate):
return round(price * (1 - rate), 2)
def compose(*funcs):
return reduce(lambda f, g: lambda x: g(f(x)), funcs, lambda x: x)
# Discount functions built in a loop: partial binds rate immediately
discounts = [partial(apply_discount, rate=r) for r in (0.1, 0.2, 0.3)]
print("discounts on 50:", [d(50) for d in discounts])
orders = [
{"id": 3, "customer": "Mya", "total": 120.0},
{"id": 1, "customer": "Aye", "total": 75.5},
{"id": 2, "customer": "Sai", "total": 120.0},
]
ranked = sorted(orders, key=operator.itemgetter("total", "id"), reverse=True)
print("ranked ids:", [o["id"] for o in ranked])
customers = map(operator.itemgetter("customer"), orders)
print("customers:", list(customers))
add_tax = partial(operator.mul, 1.05)
to_cents = partial(round, ndigits=2)
final_price = compose(partial(apply_discount, rate=0.2), add_tax, to_cents)
print("final price for 50:", final_price(50))Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Lambda က အပြင် variable တွေကို value မဟုတ်ဘဲ cell နဲ့ ကိုင်ထားပြီး ခေါ်တဲ့အချိန်မှ ဖတ်ပါတယ်။
- Loop ထဲမှာ ဆောက်တဲ့ lambda တွေ အားလုံး နောက်ဆုံး value ကို မြင်ကြပါတယ် — i=i default, partial ဒါမှမဟုတ် factory function နဲ့ ချည်ပါ။
- functools.partial က argument ကြိုဖြည့်ထားတဲ့ function ဆောက်ပြီး ဘယ်ဘက်ဆုံး မဟုတ်တဲ့ argument ကို keyword နဲ့ ချည်ပါ။
- itemgetter, attrgetter, methodcaller နဲ့ operator.add/mul က lambda တိုတိုလေးတွေကို ဖတ်ရလွယ်တဲ့ နာမည်ရှိ function တွေနဲ့ အစားထိုးပါတယ်။
- reduce နဲ့ compose လုပ်ရင် function သေးသေးလေးတွေကို pipeline တစ်ခုတည်း ဖြစ်အောင် ဆင့်ပေါင်းနိုင်ပါတယ်။
Python Documentation — Functional Programming HOWTO — Python Software Foundation