ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
Lesson 19 မှာ function ဆိုတာ ဟင်းချက်နည်း ကတ်ပြားလို့ ပြောခဲ့ပါတယ်။ အခု ကတ်ပြားပေါ်မှာ ညွှန်ကြားချက် ပိုတိကျအောင် ရေးကြည့်ပါမယ်။ "ပထမ ပစ္စည်းကို နာမည်နဲ့ မခေါ်ရ"၊ "ဆား ပမာဏကို အမြဲ နာမည်တပ်ပြီး ပြောရ"၊ "ဟင်းသီးဟင်းရွက် ကြိုက်သလောက် ထည့်လို့ရ" ဆိုတာမျိုးပါ။ ဒီလို စည်းမျဉ်းတွေက ချက်သူ မမှားအောင် ကာကွယ်ပေးပါတယ်။
ဒီ lesson က signature ကို ဒီဇိုင်းဆွဲနည်းပါ — caller တွေ မှားခေါ်လို့ မရအောင် ပုံစံချတာ၊ argument အရေအတွက် မကန့်သတ်ဘဲ လက်ခံတာ၊ function ကိုယ်တိုင်ကို တခြား function ဆီ ပို့တာနဲ့ အခြေအနေကို မှတ်ထားတဲ့ function (closure) ဖန်တီးတာတွေပါ။
Problem → Why → Solution
ပြဿနာ: call နှစ်ခုကြား cart တစ်ခုတည်းကို မျှသုံးမိတာ
Developer တစ်ယောက်က add_item(item, cart=[]) လို့ ရေးပြီး "cart မပို့ရင် cart အသစ် စမယ်" လို့ ထင်ပါတယ်။ ပထမ customer ရဲ့ ['tea'] က မှန်ပေမယ့် ဒုတိယ customer ရဲ့ cart မှာ tea ပါ ပါလာပါတယ်။ Test တစ်ခုချင်း run ရင် အောင်ပေမယ့် test တွေ အတူ run ရင် ကျပြီး production မှာ customer တစ်ယောက်ရဲ့ data က နောက်တစ်ယောက်ဆီ ပေါက်ကြားပါတယ်။
def add_item(item, cart=[]): # the list is created ONCE
cart.append(item)
return cart
print(add_item("tea")) # ['tea']
print(add_item("rice")) # ['tea', 'rice'] <- someone else's tea!
print(add_item.__defaults__) # (['tea', 'rice'],)ဘာကြောင့် ဒီလိုဖြစ်တာလဲ
Default value တွေကို def line run တဲ့အချိန် — function သတ်မှတ်တဲ့အချိန် — တစ်ခါပဲ တွက်ပြီး function object ရဲ့ __defaults__ ထဲ သိမ်းထားပါတယ်။ Call တိုင်းမှာ ဖန်တီးတာ မဟုတ်ပါဘူး။ Number နဲ့ string လို immutable default တွေမှာ ပြဿနာ မရှိပေမယ့် list, dict, set လို mutable default ကို ပြင်လိုက်ရင် နောက် call တွေအားလုံး အဲဒီ ပြင်ထားတဲ့ object ကိုပဲ ရပါတယ်။ ဖြေရှင်းနည်းက cart=None ထားပြီး body ထဲမှာ list အသစ် ဖန်တီးတာပါ။
Core concept: signature က caller ကို လမ်းပြတဲ့ စည်းမျဉ်း
Parameter list ထဲမှာ / နဲ့ * ဆိုတဲ့ marker နှစ်ခု ထည့်လို့ ရပါတယ်။ / ရဲ့ ဘယ်ဘက်က parameter တွေက positional-only ဖြစ်ပြီး နာမည်နဲ့ ပို့လို့ မရပါဘူး (Python 3.8 ကစပြီး)။ * (ဒါမှမဟုတ် *args) ရဲ့ ညာဘက်က parameter တွေက keyword-only ဖြစ်ပြီး discount=0.1 လို နာမည်နဲ့ပဲ ပို့ရပါတယ်။ Keyword-only က total(10, 20, 0.1) မှာ 0.1 ကို discount လား ဈေးနှုန်းလား ဆိုတဲ့ ရှုပ်ထွေးမှုကို ဖယ်ပေးပြီး positional-only ကတော့ parameter နာမည်ကို နောင်မှာ ပြောင်းခွင့် ပေးပါတယ်။
*args က ပိုလာတဲ့ positional argument အားလုံးကို tuple တစ်ခုအဖြစ် စုပြီး **kwargs က ပိုလာတဲ့ keyword argument အားလုံးကို dict တစ်ခုအဖြစ် စုပါတယ်။ args နဲ့ kwargs က ထုံးစံ နာမည်တွေပဲ ဖြစ်ပြီး * နဲ့ ** က အလုပ်လုပ်တာပါ။ ခေါ်တဲ့ဘက်မှာလည်း f(*numbers) နဲ့ list ကို ဖြန့်ပို့ပြီး f(**options) နဲ့ dict ကို keyword argument တွေအဖြစ် ဖြန့်ပို့လို့ ရပါတယ်။ ဒါပေမယ့် **kwargs က စာလုံးပေါင်းမှားတဲ့ option (colour= vs color=) ကိုပါ တိတ်တဆိတ် လက်ခံလို့ public API မှာ နာမည်တပ်ထားတဲ့ keyword-only parameter တွေက ပိုဘေးကင်းပါတယ်။
Python မှာ function တွေက first-class object တွေပါ — variable ထဲ ထည့်တာ၊ argument အဖြစ် ပို့တာ၊ function ကနေ return ပြန်တာ လုပ်လို့ ရပါတယ်။ sorted(words, key=len) က len function ကိုယ်တိုင်ကို ပို့တာပါ (len() လို ခေါ်ထားတာ မဟုတ်ပါ)။ Function ထဲမှာ function တစ်ခု သတ်မှတ်ပြီး return ပြန်ရင် အတွင်း function က အပြင် function ရဲ့ variable တွေကို မှတ်ထားပါတယ် — ဒါကို closure လို့ ခေါ်ပါတယ်။ အပြင် variable ကို ပြန် assign လုပ်ချင်ရင် nonlocal ကို ကြေညာရပါမယ်၊ မဟုတ်ရင် UnboundLocalError ရပါတယ်။
Type hint (def total(*prices: float, discount: float = 0.0) -> float) က parameter နဲ့ return type ကို မှတ်ချက်ပေးပါတယ်။ Python runtime က ဒါတွေကို မစစ်ပါဘူး — mypy လို tool နဲ့ editor တွေက သုံးပြီး မှားခေါ်တာကို ကြိုသတိပေးပါတယ်။ Body ရဲ့ ပထမဆုံး string ဖြစ်တဲ့ docstring က help() နဲ့ __doc__ မှာ ပေါ်ပြီး function က ဘာလုပ်လဲ၊ ဘာ return ပြန်လဲ ဆိုတာကို ရှင်းပြပါတယ်။ Hint တွေက runtime validation ကို အစားမထိုးနိုင်လို့ program အပြင်ကလာတဲ့ data ကိုတော့ ဆက်စစ်ရပါမယ်။
- / ဘယ်ဘက်: position နဲ့ပဲ
- ပိုတဲ့ positional → *args tuple
- * ညာဘက်: နာမည်နဲ့ပဲ
- ပိုတဲ့ keyword → **kwargs dict
- Default တွေ: def run ချိန် တစ်ခါ
အစဉ်က အမြဲ: positional-only, /, ပုံမှန်, *args, keyword-only, **kwargs ပါ။
အထွေထွေ ပုံစံ
def name(pos_only: T, /, normal: T, *args: T, kw_only: T = d, **kwargs: T) -> R:
"""One-line summary of what the function returns."""
...
def name(items: list[T] | None = None) -> list[T]:
if items is None:
items = [] # fresh object on every call
def outer(setting: T) -> Callable[[A], R]:
def inner(arg: A) -> R:
return use(setting, arg) # inner remembers setting
return innerပထမ signature က parameter အမျိုးအစား ခြောက်မျိုးကို မှန်ကန်တဲ့ အစဉ်နဲ့ ပြပါတယ်။ ဒုတိယက mutable default အစား None sentinel ကို သုံးတဲ့ ပုံစံ၊ တတိယက setting ကို မှတ်ထားတဲ့ function ကို ပြန်ပေးတဲ့ closure ပုံစံပါ။
Example: report, tag, counter နဲ့ option တွေ
Function လေးခုက ဒီ lesson ရဲ့ အချက်တစ်ခုစီကို ပြပါတယ်။ make_report က / နဲ့ *rows နဲ့ keyword-only option တွေ၊ add_tag က mutable default ကို ဘေးကင်းအောင် ပြင်ထားတာ၊ make_counter က nonlocal closure၊ describe က **kwargs ပါ။ နောက်ဆုံးမှာ positional-only parameter ကို နာမည်နဲ့ ပို့ရင် ဘာဖြစ်လဲ ကြည့်ပါမယ်။
from collections.abc import Callable
def make_report(title: str, /, *rows: str, sep: str = "-", width: int = 12) -> str:
"""Return a title, a rule line, then one row per line."""
return "\n".join([title, sep * width, *rows])
def add_tag(tag: str, tags: list[str] | None = None) -> list[str]:
if tags is None:
tags = []
tags.append(tag)
return tags
def make_counter(start: int = 0) -> Callable[[], int]:
count = start
def step() -> int:
nonlocal count
count += 1
return count
return step
def describe(**options: object) -> str:
return ", ".join(f"{key}={value}" for key, value in options.items())
print(make_report("Sales", "Mon 120", "Tue 95", sep="=", width=10))
print(add_tag("a"), add_tag("b"))
counter = make_counter(10)
print(counter(), counter(), counter())
print(describe(debug=True, retries=3))
print(make_report.__doc__)
try:
make_report(title="Sales")
except TypeError as err:
print("TypeError:", err)Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Line 4
def make_report(title: str, /, *rows: str, sep: str = "-", width: int = 12) -> str:title က / ရှေ့မှာ ရှိလို့ positional-only ပါ။ *rows က ကျန်တဲ့ positional string တွေကို tuple အဖြစ် စုပြီး sep နဲ့ width က *rows နောက်မှာ ရှိလို့ keyword-only ဖြစ်ကာ sep="=" လို နာမည်နဲ့ပဲ ပို့ရပါတယ်။
- Lines 9-11
if tags is None:Default က None (immutable) ဖြစ်ပြီး call တိုင်းမှာ list အသစ် ဖန်တီးလို့ add_tag("a") နဲ့ add_tag("b") က ['a'] နဲ့ ['b'] သီးခြားစီ ရပါတယ် — problem section ရဲ့ bug မရှိတော့ပါဘူး။
- Lines 19-22
nonlocal countstep() က make_counter ရဲ့ count ကို မှတ်ထားတဲ့ closure ပါ။ nonlocal မပါရင် count += 1 က local variable အသစ်လို့ ယူဆပြီး UnboundLocalError ဖြစ်ပါတယ်။ counter() ကို ခေါ်တိုင်း 11, 12, 13 ဆက်တိုးပါတယ်။
- Line 27
def describe(**options: object) -> str:**options က debug=True, retries=3 ကို {'debug': True, 'retries': 3} dict အဖြစ် လက်ခံပြီး ပို့ခဲ့တဲ့ အစဉ်အတိုင်း ပြန်ထုတ်ပါတယ်။
- Lines 38-41
make_report(title="Sales")title က positional-only ဖြစ်လို့ နာမည်နဲ့ ပို့ရင် TypeError တက်ပါတယ်။ Error message က ဘယ် parameter မှားလဲ ဆိုတာကို တိတိကျကျ ပြောပါတယ်။
Sales
==========
Mon 120
Tue 95
['a'] ['b']
11 12 13
debug=True, retries=3
Return a title, a rule line, then one row per line.
TypeError: make_report() got some positional-only arguments passed as keyword arguments: 'title'
Function ကို value အဖြစ် ပို့ခြင်း
Function ကို parentheses မပါဘဲ ရေးရင် function object ကိုယ်တိုင် ဖြစ်လို့ variable ထဲ ထည့်ပြီး နောက်မှ ခေါ်လို့ ရပါတယ်။ apply_each က ဘာလုပ်ရမလဲဆိုတဲ့ "အပြုအမူ" ကို argument အဖြစ် လက်ခံတဲ့ higher-order function ပါ။ sorted() ရဲ့ key parameter၊ map() နဲ့ decorator တွေ (နောက်ပိုင်း lesson မှာ အသေးစိတ် လေ့လာပါမယ်) အားလုံး ဒီ အယူအဆ ပေါ်မှာ အခြေခံပါတယ်။
def shout(text: str) -> str:
return text.upper() + "!"
def whisper(text: str) -> str:
return text.lower() + "..."
def apply_each(func, items):
return [func(item) for item in items]
style = shout # no parentheses: the function itself
print(style("hi")) # HI!
print(apply_each(whisper, ["Hello", "BYE"]))
print(sorted(["kiwi", "fig", "banana"], key=len))လက်တွေ့ project တွေမှာ
Real project တွေမှာ ဘယ်လို သုံးလဲ
Report generator တစ်ခုကို generate_report(rows, *, title, clock, writer) လို ဒီဇိုင်းဆွဲပါတယ်။ title နဲ့ option တွေက keyword-only ဖြစ်လို့ ခေါ်တဲ့ code က ဖတ်ရလွယ်ပြီး argument အစဉ်မှားတာ မဖြစ်တော့ပါဘူး။ clock (လက်ရှိ အချိန်ကို ပေးတဲ့ function) နဲ့ writer (output ကို ရေးတဲ့ function) ကို argument အဖြစ် ထိုးသွင်းထား (inject) လို့ test မှာ အချိန် အသေ ပေးတဲ့ function နဲ့ list ထဲ စုတဲ့ function ကို ပို့ပြီး file နဲ့ နာရီ မလိုဘဲ ရလဒ်ကို တိတိကျကျ စစ်နိုင်ပါတယ်။
Python ရဲ့ standard library ကိုယ်တိုင်က ဒီနည်းတွေကို သုံးပါတယ် — sorted() ရဲ့ key နဲ့ reverse က keyword-only ဖြစ်ပြီး len() လို built-in အများစုက positional-only ပါ။ Web framework တွေက route handler function တွေကို registry ထဲ သိမ်းထားပြီး request ရောက်မှ ခေါ်ပါတယ်။ Logging wrapper လို code တွေက *args, **kwargs ကို လက်ခံပြီး မူရင်း function ဆီ အပြောင်းအလဲ မရှိ ဆက်ပို့ပါတယ်။ Team project တွေမှာ public function တိုင်းကို type hint နဲ့ docstring ထည့်ထားလို့ editor က hover လုပ်တာနဲ့ အသုံးပြုပုံ ပြပြီး mypy က CI မှာ type မကိုက်တာကို ဖမ်းပါတယ်။
အမှားများ
အဖြစ်များတဲ့ အမှားတွေ
1. Mutable value ကို default ထားတာ
def add_item(item, cart=[]) နဲ့ def register(user, roles={}) တို့က call တိုင်း object တစ်ခုတည်းကို မျှသုံးပါတယ်။ Default ကို None ထားပြီး body ထဲမှာ if cart is None: cart = [] လို့ ရေးပါ။ if not cart: လို့ မရေးပါနဲ့ — caller ပို့လိုက်တဲ့ empty list ကိုပါ အစားထိုးသွားလို့ပါ။
2. **kwargs နဲ့ option တွေကို ဖုံးထားတာ
def connect(**kwargs) က connect(tiemout=5) လို စာလုံးပေါင်းမှားတာကို error မပေးဘဲ လက်ခံပြီး timeout ကို တိတ်တဆိတ် လျစ်လျူရှုပါတယ်။ သိပြီးသား option တွေကို def connect(*, timeout=10, retries=3) လို keyword-only parameter အဖြစ် ရေးပါ၊ အဲဒီအခါ typo က TypeError ဖြစ်လာပါတယ်။
3. nonlocal မပါဘဲ closure variable ကို ပြင်တာ
Inner function ထဲမှာ count += 1 လို့ ရေးပြီး nonlocal count မကြေညာရင် UnboundLocalError: cannot access local variable 'count' where it is not associated with a value ရပါတယ်။ Assignment တစ်ခု ရှိတာနဲ့ Python က အဲဒီ နာမည်ကို local လို့ ဆုံးဖြတ်လို့ပါ။
4. Function ကို ပို့မယ့်အစား ခေါ်လိုက်တာ
sorted(words, key=len()) က len ကို argument မပါဘဲ ခေါ်လို့ TypeError ဖြစ်ပြီး apply_each(shout(), items) ကလည်း အတူတူပါ။ Function ကို ပို့တဲ့အခါ parentheses မထည့်ပါနဲ့: key=len, apply_each(shout, items)။
Best Practices
အကောင်းဆုံး အလေ့အကျင့်များ
- Boolean flag နဲ့ ရှားရှားပါးပါး သုံးတဲ့ option တွေကို * နောက်မှာ keyword-only အဖြစ် ထားပါ။
- Public function တိုင်းမှာ type hint နဲ့ ဘာ return ပြန်လဲ ပြောတဲ့ တစ်ကြောင်း docstring ထည့်ပါ။
- Side effect (အချိန်၊ file၊ network) ကို function ထဲမှာ တိုက်ရိုက် မခေါ်ဘဲ argument အဖြစ် ပို့ပေးပါ၊ test လုပ်ရ လွယ်ပါတယ်။
Mini challenge
Mini challenge: ဈေးနှုန်း toolkit
ဒီ lesson ရဲ့ technique လေးမျိုးကို သုံးတဲ့ function လေးခုပါတဲ့ ဈေးနှုန်း toolkit တစ်ခု ရေးပါ။ Function တိုင်းမှာ type hint နဲ့ docstring ပါရပါမယ်။
- total(*prices, discount=0.0) — ဈေးနှုန်း ကြိုက်သလောက် လက်ခံပြီး discount က keyword-only ဖြစ်ရမယ်၊ ဒသမ နှစ်နေရာ round
- make_discount(percent) — ဈေးတစ်ခုကို ရာခိုင်နှုန်း လျှော့ပေးတဲ့ function ကို return ပြန်တဲ့ closure
- apply_all(prices, rule) — rule function ကို ဈေးနှုန်းတိုင်းပေါ် apply လုပ်ပြီး list ပြန်ရမယ်
- add_item(item, cart=None) — mutable default bug မရှိရ
- total.__doc__ ကို print ပြပြီး make_discount() ကို argument မပါဘဲ ခေါ်တဲ့ TypeError ကို ဖမ်းပြရမယ်
from collections.abc import Callable
def total(*prices: float, discount: float = 0.0) -> float:
"""TODO: one-line docstring"""
# TODO: sum the prices, apply the discount, round to 2 decimals
...
def make_discount(percent: float) -> Callable[[float], float]:
# TODO: define an inner function that discounts one price, then return it
...
def apply_all(prices: list[float], rule: Callable[[float], float]) -> list[float]:
# TODO: return a new list with rule applied to each price
...
def add_item(item: str, cart: list[str] | None = None) -> list[str]:
# TODO: create a fresh list when cart is None, then append
...
# TODO: try total(10, 20, 5), the same with discount=0.1, and total(10, 20, 0.1)
# TODO: ten_off = make_discount(10); apply it to [100.0, 59.9]
# TODO: call add_item twice without a cart; print total.__doc__
# TODO: call make_discount() inside try/except TypeErrorရလဒ်: Output က ဒီလို ဖြစ်ရပါမယ်: 35.0 31.5 30.1 [90.0, 53.91] ['tea'] ['rice'] Sum any number of prices, then take off a fractional discount. TypeError: make_discount() missing 1 required positional argument: 'percent'
အရိပ်အမြွက် ကြည့်ရန်
total(10, 20, 0.1) က 0.1 ကို ဈေးနှုန်း တစ်ခုလို့ ယူလို့ 30.1 ရပါတယ် — discount ကို keyword-only ထားရတဲ့ အကြောင်းရင်းပါ။ Closure ထဲမှာ percent ကို ဖတ်ရုံပဲ လုပ်လို့ nonlocal မလိုပါဘူး။
အဖြေ ကြည့်ရန်
from collections.abc import Callable
def total(*prices: float, discount: float = 0.0) -> float:
"""Sum any number of prices, then take off a fractional discount."""
return round(sum(prices) * (1 - discount), 2)
def make_discount(percent: float) -> Callable[[float], float]:
"""Return a function that applies a fixed percentage discount."""
def apply(price: float) -> float:
return round(price * (1 - percent / 100), 2)
return apply
def apply_all(prices: list[float], rule: Callable[[float], float]) -> list[float]:
"""Run one pricing rule on every price."""
return [rule(price) for price in prices]
def add_item(item: str, cart: list[str] | None = None) -> list[str]:
"""Add an item to a cart, creating a fresh cart when none is given."""
if cart is None:
cart = []
cart.append(item)
return cart
print(total(10, 20, 5))
print(total(10, 20, 5, discount=0.1))
print(total(10, 20, 0.1))
ten_off = make_discount(10)
print(apply_all([100.0, 59.9], ten_off))
print(add_item("tea"), add_item("rice"))
print(total.__doc__)
try:
make_discount()
except TypeError as err:
print("TypeError:", err)Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- / ရှေ့က parameter တွေ positional-only၊ * နောက်က parameter တွေ keyword-only ဖြစ်ပါတယ်။
- *args က tuple၊ **kwargs က dict အဖြစ် ပိုလာတဲ့ argument တွေကို စုပြီး ခေါ်တဲ့ဘက်မှာ * နဲ့ ** က ဖြန့်ပေးပါတယ်။
- Default တွေကို def ချိန်မှာ တစ်ခါပဲ တွက်လို့ mutable default အစား None sentinel ကို သုံးပါ။
- Function တွေက value ဖြစ်လို့ ပို့လို့၊ return ပြန်လို့ ရပြီး closure က အပြင် variable ကို မှတ်ထားပါတယ် (ပြန် assign ဖို့ nonlocal)။
- Type hint နဲ့ docstring က tool နဲ့ လူကို လမ်းပြပေမယ့် runtime validation ကို အစားမထိုးပါဘူး။
Python Documentation — Functional Programming HOWTO — Python Software Foundation