ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
Code ကို computer အတွက်ထက် လူအတွက် ပိုရေးတာပါ။ Computer က x, d, proc လို နာမည်တွေကို ပြဿနာမရှိ run ပေးပါတယ်။ ဒါပေမယ့် နောက်လမှာ ပြန်ဖတ်မယ့် ကိုယ်တိုင် ဒါမှမဟုတ် team ထဲက တခြားသူက အဲဒီ code ဘာလုပ်လဲ နားလည်ဖို့ မိနစ်ပေါင်းများစွာ ကုန်ပါမယ်။
Best practice တွေဆိုတာ Python community က သဘောတူထားတဲ့ စည်းကမ်းတွေပါ။ နာမည်ပေးပုံ၊ indent လုပ်ပုံ (space 4 ခု)၊ function တစ်ခုကို အလုပ်တစ်ခုပဲ ပေးတာ၊ bug ဖြစ်လွယ်တဲ့ ထောင်ချောက်တွေကို ရှောင်တာ စတာတွေ ပါပါတယ်။ စည်းကမ်းတွေ တူနေရင် ဘယ် Python project ကို ဖွင့်ဖွင့် ရင်းနှီးနေသလို ခံစားရပါတယ်။
Problem → Why → Solution
ပြဿနာ: run လို့ရပေမယ့် ဖတ်လို့ မရတဲ့ code
အောက်က proc() function က ပထမအကြိမ် ခေါ်တုန်းက မှန်ပါတယ်။ ဒုတိယအကြိမ်မှာတော့ 1000 တစ်ခုတည်းရဲ့ 20% (200.0) ရမယ့်အစား 5566.67 ခန့်ကို ပြန်ပေးပါတယ်။ နာမည်တွေက ဘာမှ မပြောပြလို့ ဘာကို တွက်နေလဲ ခန့်မှန်းရပြီး bare except: က အမှားမှန်သမျှကို 0 အဖြစ် ဖုံးထားပါတယ်။
def proc(d, l=[]):
for x in d:
if x != None and x > 0: l.append(x * 0.2)
try:
return sum(l) / len(l)
except:
return 0
print(proc([50000, None, 32500])) # 8250.0
print(proc([1000])) # 5566.666..., not 200.0: old values remainဘာကြောင့် ဒီလို ဖြစ်ရတာလဲ
Default value l=[] ကို function ကို define လုပ်တဲ့အချိန် တစ်ကြိမ်ပဲ ဖန်တီးပါတယ်၊ ခေါ်တိုင်း အသစ် မဖန်တီးပါဘူး။ ဒါကြောင့် ပထမ call က ထည့်ခဲ့တဲ့ value တွေ list ထဲ ကျန်နေပါတယ်။ အဲဒီ bug ကို နာမည်မရှင်းတာ၊ bare except နဲ့ line တစ်ကြောင်းထဲ ထည့်ရေးတာတွေက ဖုံးကွယ်ထားလို့ ရှာရ ခက်ပါတယ်။
Core concept: ဖတ်ရလွယ်ခြင်းက feature တစ်ခုပါ
Python ရဲ့ style guide က PEP 8 ပါ။ Indent အတွက် space 4 ခု သုံးပြီး line တစ်ကြောင်းကို character 79 ခုအထိ ထားဖို့ အကြံပြုပါတယ် (team အများစုက formatter နဲ့ အနည်းငယ် ပိုရှည်တဲ့ limit ကို သဘောတူ သုံးကြပါတယ်)။ အရေးကြီးဆုံးကတော့ naming ပါ — နာမည်ပုံစံကို ကြည့်တာနဲ့ အဲဒီ နာမည်က ဘာအမျိုးအစားလဲ သိရပါတယ်။
| အမျိုးအစား | ပုံစံ | ဥပမာ |
|---|---|---|
| Variable, function | snake_case | total_price, calculate_tax() |
| Class | PascalCase | Employee, OrderItem |
| Constant | UPPER_SNAKE_CASE | TAX_RATE, MAX_RETRIES |
| Internal (private သဘော) | _leading_underscore | _cache, _parse_row() |
Function တစ်ခုက အလုပ်တစ်ခုပဲ လုပ်သင့်ပြီး အဲဒီ အလုပ်ကို နာမည်က ပြောပြရပါမယ်။ calculate_tax() က tax တွက်ရုံပဲ လုပ်ပြီး file ရေးတာ၊ print ထုတ်တာကို ခေါ်တဲ့သူဆီ ချန်ထားရင် test ရေးရလွယ်ပြီး နေရာတိုင်းမှာ ပြန်သုံးလို့ ရပါတယ်။ Type hint (income: float) -> float က ဘာလက်ခံလဲ၊ ဘာပြန်ပေးလဲ ပြောပြပြီး docstring က ဘာကြောင့် ရှိလဲ ရှင်းပြပါတယ်။ Type hint တွေကို Python က runtime မှာ မစစ်ပါဘူး — mypy လို type checker နဲ့ editor တွေက သုံးတာပါ။
အမှားတွေကိုလည်း ရှင်းရှင်းလင်းလင်း ကိုင်တွယ်ပါ။ Data မှားရင် 0 ဒါမှမဟုတ် None ကို တိတ်တိတ်လေး ပြန်မပေးဘဲ ValueError လို exception ကို message နဲ့ raise လုပ်ပါ။ None နဲ့ နှိုင်းယှဉ်တဲ့အခါ == အစား is ကို သုံးပါ၊ None က object တစ်ခုတည်းသာ ရှိပြီး class တစ်ခုက == ကို override လုပ်ထားနိုင်လို့ပါ။ Default value အဖြစ် list, dict လို mutable object တွေ မထားဘဲ None ထားပြီး function ထဲမှာ အသစ် ဖန်တီးပါ။
Comment နဲ့ docstring က အလုပ်မတူပါဘူး။ Docstring က function ကို ခေါ်မယ့်သူအတွက် ဘာလုပ်လဲ ဖော်ပြပြီး help() လို tool တွေက ပြပေးပါတယ်။ Comment ကတော့ line တစ်ကြောင်းကို ဘာကြောင့် ဒီလို ရေးထားလဲ ရှင်းပြပါတယ် — ဥပမာ tax ကို ဘာကြောင့် cent အထိ round လုပ်လဲ ဆိုတာမျိုးပါ။ # x ကို 1 ပေါင်း လို code ကို ထပ်ပြောရုံ comment က အသုံးမဝင်တဲ့ အသံဆူညံမှုပဲ ဖြစ်ပြီး တစ်ယောက်ယောက် line ကို ပြင်လိုက်တာနဲ့ မမှန်တော့ပါဘူး။
- နာမည်က ဘာလဲ ပြောပြလား
- Function က အလုပ်တစ်ခုပဲ လုပ်လား
- Hint နဲ့ docstring က contract ပြလား
- အမှားကို ကျယ်ကျယ် ပြောလား
ခြောက်လကြာမှ code ကို ပြန်ဖွင့်တဲ့ ကိုယ့်ကိုယ်ကို ဒီမေးခွန်း လေးခုနဲ့ ကူညီပါ။
အထွေထွေ ပုံစံ
CONSTANT_NAME = value
def function_name(param: Type, option: Type | None = None) -> ReturnType:
"""One line saying what the function returns or does."""
if option is None:
option = make_fresh_default()
if not is_valid(param):
raise ValueError("clear message about what is wrong")
return resultConstant က UPPER_SNAKE_CASE၊ function က snake_case ပါ။ Parameter နဲ့ return မှာ type hint ပါပြီး docstring က ပထမဆုံး statement ဖြစ်ပါတယ်။ Mutable default လိုရင် None ထားပြီး is None နဲ့ စစ်ကာ အသစ် ဖန်တီးပါတယ်။ Input မှားရင် exception raise လုပ်ပါတယ်။
Example: ရှင်းလင်းအောင် ပြန်ရေးထားတဲ့ tax code
ဒီ example က problem section ထဲက အမှားတွေကို တစ်ခုချင်း ဖြေရှင်းထားပါတယ်။ Dataclass တစ်ခုက ဝန်ထမ်း data ကို ဖွဲ့စည်းပေးပြီး calculate_tax() က input မှားရင် ValueError raise လုပ်ပါတယ်။ add_tag() ကတော့ mutable default ထောင်ချောက်ကို None default နဲ့ ရှောင်ထားပါတယ်။
from dataclasses import dataclass
TAX_RATE = 0.2 # module-level constant: UPPER_SNAKE_CASE
@dataclass
class Employee: # classes use PascalCase
name: str
income: float
def calculate_tax(income: float, tax_rate: float = TAX_RATE) -> float:
"""Return the tax owed on a yearly income, rounded to cents."""
if income < 0:
raise ValueError("income cannot be negative")
return round(income * tax_rate, 2)
def add_tag(tag: str, tags: list[str] | None = None) -> list[str]:
"""Add a tag to the caller's list, or to a brand-new list."""
if tags is None: # compare with None using 'is'
tags = []
tags.append(tag)
return tags
staff = [Employee("Aye", 50_000), Employee("Ko Ko", 32_500.5)]
taxes = [calculate_tax(person.income) for person in staff]
print(f"Taxes: {taxes}")
print(add_tag("new"), add_tag("vip"))
try:
calculate_tax(-1)
except ValueError as err:
print(f"Rejected: {err}")Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Line 3
TAX_RATE = 0.2 # module-level constant: UPPER_SNAKE_CASECode ထဲ 0.2 ကို နေရာအနှံ့ ရေးမယ့်အစား နာမည်ရှိတဲ့ constant တစ်ခုထဲ ထားပါတယ်။ Tax rate ပြောင်းရင် တစ်နေရာတည်းမှာ ပြင်ရုံပါပဲ။
- Lines 6-9
class Employee: # classes use PascalCase@dataclass က __init__ နဲ့ __repr__ ကို အလိုအလျောက် ရေးပေးပါတယ်။ person["income"] လို dict key string တွေထက် person.income က typo ဖြစ်ရင် editor က ချက်ချင်း သတိပေးနိုင်ပါတယ်။
- Lines 14-15
raise ValueError("income cannot be negative")Income အနုတ်ဆိုတာ data မှားတာပါ။ 0 ပြန်ပေးရင် report ထဲမှာ မှားတဲ့ ဂဏန်း တိတ်တိတ်လေး ဝင်သွားမှာမို့ exception နဲ့ ကျယ်ကျယ် ပြောပါတယ်။
- Lines 21-22
if tags is None: # compare with None using 'is'tags=None ကို default ထားပြီး call တိုင်းမှာ list အသစ် ဖန်တီးလို့ add_tag("new") နဲ့ add_tag("vip") က list သီးခြားစီ ရပါတယ်။ Output မှာ ['new'] ['vip'] လို့ ထွက်တာ သက်သေပါ။
- Line 28
taxes = [calculate_tax(person.income) for person in staff]List comprehension က "ဝန်ထမ်းတိုင်းအတွက် tax" ဆိုတဲ့ အဓိပ္ပာယ်ကို တစ်ကြောင်းတည်းနဲ့ ပြောပါတယ်။ 32500.5 × 0.2 ကို round() လုပ်ထားလို့ 6500.1 ရပါတယ်။
Taxes: [10000.0, 6500.1]
['new'] ['vip']
Rejected: income cannot be negativeMutable default argument ကို ကိုယ်တိုင် စမ်းကြည့်ပါ
Default value တွေကို function object ပေါ်မှာ __defaults__ အဖြစ် သိမ်းထားပါတယ်။ အောက်က code ကို run ကြည့်ရင် call နှစ်ခုက list တစ်ခုတည်းကို မျှသုံးနေတာ မြင်ရပါမယ်။ Tuple, str, int, None လို immutable default တွေကတော့ ပြောင်းလဲလို့ မရလို့ ဘေးကင်းပါတယ်။
def remember(item, seen=[]):
seen.append(item)
return seen
print(remember("a")) # ['a']
print(remember("b")) # ['a', 'b'] <- the same list again
print(remember.__defaults__) # (['a', 'b'],)စည်းကမ်းတွေကို tool တွေနဲ့ အလိုအလျောက် စစ်ပါ
Style စည်းကမ်းတွေကို code review မှာ လူက လိုက်စစ်နေရင် အချိန်ကုန်ပြီး ငြင်းခုံစရာ ဖြစ်ပါတယ်။ Tool တွေကို editor မှာ save လုပ်တိုင်း ဒါမှမဟုတ် CI မှာ run အောင် ထားလိုက်ရင် review က logic ပေါ်မှာပဲ အာရုံစိုက်လို့ ရပါတယ်။
| Tool | အလုပ် |
|---|---|
| Black ဒါမှမဟုတ် ruff format | Code ပုံစံကို အလိုအလျောက် ပြန်စီ (formatter) |
| Ruff | Unused import, bare except လို ပြဿနာတွေ ရှာ (linter) |
| mypy | Type hint တွေနဲ့ မကိုက်တဲ့ call တွေ ရှာ (type checker) |
| pytest | Function တွေ မှန်ကန်ကြောင်း test တွေ run |
လက်တွေ့ project တွေမှာ
Real project တွေမှာ ဘယ်လို သုံးလဲ
Team project တွေမှာ ဒီစည်းကမ်းတွေကို pyproject.toml ထဲမှာ ရေးထားပြီး pre-commit hook နဲ့ CI pipeline က commit တိုင်းမှာ formatter, linter, type checker နဲ့ test တွေကို run ပါတယ်။ တစ်ခုခု fail ရင် pull request ကို merge လုပ်လို့ မရပါဘူး။ ဒါကြောင့် "tab သုံးမလား space သုံးမလား" လို ငြင်းခုံမှုတွေ မရှိတော့ဘဲ review က business logic ပေါ်မှာပဲ အာရုံစိုက်ပါတယ်။
Script ရှည်ကြီး တစ်ခုကို refactor လုပ်ရတဲ့အခါ ဒီ lesson ရဲ့ ပုံစံကို လိုက်ပါ — config (constant တွေ)၊ input ဖတ်တာ၊ တွက်ချက်တဲ့ logic နဲ့ output ရေးတာကို function သီးခြားစီ ခွဲပါ။ Logic function တွေက file ဒါမှမဟုတ် network ကို မထိတော့လို့ pytest နဲ့ input/output test လွယ်လွယ်ကူကူ ရေးလို့ ရပါတယ်။ Input ကို system ထဲ ဝင်တဲ့ နေရာမှာတင် validate လုပ်လိုက်ရင် အတွင်းပိုင်း function တွေက data မှန်ပြီးသားလို့ ယုံလို့ ရပါတယ်။
အမှားများ
အဖြစ်များတဲ့ အမှားတွေ
1. List ဒါမှမဟုတ် dict ကို default argument ထားတာ
def add(item, items=[]) က call တိုင်း list တစ်ခုတည်းကို မျှသုံးလို့ value တွေ call တစ်ခုကနေ နောက်တစ်ခုဆီ ယိုစိမ့်ပါတယ်။ items=None ထားပြီး if items is None: items = [] နဲ့ အသစ် ဖန်တီးပါ။ Ruff လို linter က ဒီပုံစံကို ဖမ်းပေးနိုင်ပါတယ်။
2. Bare except: နဲ့ အမှားအားလုံး ဖမ်းတာ
except: က KeyboardInterrupt (Ctrl+C) အပါအဝင် exception မှန်သမျှကို ဖမ်းပြီး ကိုယ်မမျှော်လင့်တဲ့ bug တွေကိုပါ ဖုံးပစ်ပါတယ်။ except ZeroDivisionError: လို ကိုယ်ကိုင်တွယ်နိုင်တဲ့ type ကိုပဲ နာမည်တပ် ဖမ်းပါ။
3. DRY အတွက် မဆိုင်တဲ့ rule တွေကို ပေါင်းတာ
Code နှစ်နေရာ ဆင်တူနေတိုင်း function တစ်ခုထဲ ပေါင်းဖို့ မလိုပါဘူး။ Tax rule နဲ့ shipping rule က ဒီနေ့ တူနေပေမယ့် နောက်လ သီးခြားစီ ပြောင်းနိုင်ပါတယ်။ Flag parameter တွေ များလာတဲ့ "generic" function တစ်ခုထက် ရှင်းလင်းတဲ့ function နှစ်ခုက ပိုကောင်းပါတယ်။
Best Practices
အကောင်းဆုံး အလေ့အကျင့်များ
- Project တိုင်းအတွက် virtual environment သီးသန့် သုံးပြီး dependency version တွေကို ဖိုင်တစ်ခုထဲ မှတ်ထားပါ။
- Code ကို မြန်အောင် ပြင်ခင် cProfile နဲ့ ဘယ်နေရာက တကယ် နှေးလဲ တိုင်းပါ၊ ခန့်မှန်းပြီး မပြင်ပါနဲ့။
- Global variable တွေကို ပြောင်းနေမယ့်အစား လိုတဲ့ data ကို parameter အဖြစ် ပို့ပြီး ရလဒ်ကို return ပြန်ပါ။
- File ဖွင့်တဲ့အခါ with block ကို အမြဲ သုံးပါ၊ error ဖြစ်လည်း file ကို ပိတ်ပေးပါတယ်။
Mini challenge
Mini challenge: order script ကို refactor လုပ်ပါ
"name, amount" ပုံစံ စာကြောင်းတွေကို ဖတ်ပြီး customer တစ်ယောက်ချင်းရဲ့ စုစုပေါင်းကို တွက်တဲ့ code ကို ဒီ lesson ရဲ့ စည်းကမ်းတွေနဲ့ ရေးပါ။ Amount အနုတ်ပါတဲ့ စာကြောင်းကို ကျော်ပြီး အကြောင်းပြချက် print ထုတ်ရပါမယ်။
- customer နဲ့ amount field ပါတဲ့ Order dataclass တစ်ခု
- parse_order(line) -> Order က amount အနုတ်ဆိုရင် ValueError raise လုပ်ရမယ်
- total_by_customer(orders) -> dict[str, float] က mutable default argument မသုံးရ
- Function တိုင်းမှာ type hint နဲ့ docstring ပါရမယ်
from dataclasses import dataclass
@dataclass
class Order:
# TODO: a customer (str) field and an amount (float) field
...
def parse_order(line: str) -> Order:
# TODO: docstring
# TODO: split on the comma, strip the spaces, convert the amount with float()
# TODO: raise ValueError for a negative amount
...
def total_by_customer(orders: list[Order]) -> dict[str, float]:
# TODO: docstring, then sum the amounts per customer into a new dict
...
lines = ["Aye, 12.5", "Ko Ko, 8", "Aye, 7.5", "Mya, -3"]
# TODO: parse each line, print "Skipped: <reason>" for bad ones, then print the totalsရလဒ်: Program က ဒီလို print ထုတ်ရပါမယ်: Skipped: negative amount for Mya {'Aye': 20.0, 'Ko Ko': 8.0}
အရိပ်အမြွက် ကြည့်ရန်
name, raw_amount = line.split(",") နဲ့ နှစ်ပိုင်း ခွဲပါ။ Dict ထဲ ပေါင်းထည့်ဖို့ totals.get(name, 0.0) + amount ကို သုံးပါ။ parse_order() ကို try/except ValueError ထဲမှာ ခေါ်ပါ။
အဖြေ ကြည့်ရန်
from dataclasses import dataclass
@dataclass
class Order:
customer: str
amount: float
def parse_order(line: str) -> Order:
"""Turn a 'name, amount' line into an Order, rejecting negative amounts."""
name, raw_amount = line.split(",")
amount = float(raw_amount)
if amount < 0:
raise ValueError(f"negative amount for {name.strip()}")
return Order(name.strip(), amount)
def total_by_customer(orders: list[Order]) -> dict[str, float]:
"""Return the summed order amount for each customer."""
totals: dict[str, float] = {}
for order in orders:
totals[order.customer] = totals.get(order.customer, 0.0) + order.amount
return totals
lines = ["Aye, 12.5", "Ko Ko, 8", "Aye, 7.5", "Mya, -3"]
orders: list[Order] = []
for line in lines:
try:
orders.append(parse_order(line))
except ValueError as err:
print(f"Skipped: {err}")
print(total_by_customer(orders))Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- PEP 8: space 4 ခု indent၊ snake_case function/variable၊ PascalCase class၊ UPPER_SNAKE_CASE constant။
- Function တစ်ခုကို အလုပ်တစ်ခုပဲ ပေးပြီး type hint နဲ့ docstring နဲ့ သူ့ contract ကို ပြပါ။
- Mutable default argument မသုံးပါနဲ့ — None ထားပြီး is None နဲ့ စစ်ပါ။
- Data မှားရင် exception raise လုပ်ပြီး formatter, linter, type checker, test ကို tool တွေနဲ့ အလိုအလျောက် run ပါ။
The Python Tutorial — Python Software Foundation