ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
ဆေးရုံမှာ လူနာတွေကို "တတိယခုတင်က လူ" လို့ မမှတ်ဘဲ လူနာနံပါတ်နဲ့ မှတ်ပါတယ်။ လူနာတစ်ယောက် ဆင်းသွားလို့ ခုတင်ရွှေ့ရင် "တတိယခုတင်" က တခြားလူ ဖြစ်သွားနိုင်ပေမဲ့ လူနာနံပါတ်ကတော့ မပြောင်းပါဘူး။ To-do app မှာ task တစ်ခုစီကို အဲဒီလို မပြောင်းတဲ့ id နံပါတ် ပေးပါမယ်။
App ကို အပိုင်းသုံးပိုင်း ခွဲပါမယ်။ Task တွေကို ကိုင်တွယ်တဲ့ စည်းကမ်းတွေ (domain)၊ file ထဲ သိမ်းတာ/ပြန်ဖတ်တာ (storage) နဲ့ screen ပေါ် ပြတာ (presentation) ပါ။ အပိုင်းတစ်ခုကို ပြောင်းတဲ့အခါ ကျန်တဲ့ အပိုင်းတွေကို မထိရပါဘူး။
Problem → Why → Solution
ပြဿနာ: "delete 2" က မှားတဲ့ task ကို ဖျက်တာ
Task တွေကို string list အဖြစ် tasks.txt ထဲ သိမ်းပြီး enumerate(tasks, 1) နဲ့ နံပါတ်တပ်ပြတဲ့ ရိုးရိုး app တစ်ခုကို စိတ်ထဲ မြင်ကြည့်ပါ။ User က list ကို ကြည့်ပြီး "2 ကို ဖျက်မယ်" လို့ ဆုံးဖြတ်ပါတယ်။ အဲဒီကြားမှာ တခြား command တစ်ခုက task 1 ကို ဖျက်လိုက်ရင် နံပါတ်တွေ အားလုံး တစ်နေရာစီ ရွှေ့သွားလို့ "2" က user မြင်ခဲ့တဲ့ task မဟုတ်တော့ပါဘူး။
List ကို alphabet အလိုက် စီပြလိုက်ရင်လည်း ဒီပြဿနာ ဖြစ်ပါတယ်။ String list မှာ done/not done ဆိုတဲ့ status ကို သိမ်းစရာ နေရာလည်း မရှိပါဘူး။ save_tasks() က file ကို တိုက်ရိုက် overwrite လုပ်ရင် ရေးနေတုန်း program ပိတ်သွားတဲ့အခါ file တစ်ဝက်ပဲ ကျန်ပြီး task တွေ ပျောက်နိုင်ပါတယ်။
tasks = ["Buy milk", "Call Mya", "Pay rent"]
# The user sees: 1. Buy milk 2. Call Mya 3. Pay rent
# and wants to delete "Call Mya" by typing 2 ...
tasks.pop(0) # ... but another command removed task 1 first
tasks.pop(2 - 1) # deletes "Pay rent", not "Call Mya"
print(tasks) # ['Call Mya']ဘာကြောင့် ဒီလိုဖြစ်တာလဲ
List position က item ရဲ့ identity မဟုတ်ပါဘူး။ "လက်ရှိ ဘယ်နေရာမှာ ရှိလဲ" ဆိုတာကိုပဲ ပြောပြီး insert၊ delete၊ sort တိုင်းမှာ ပြောင်းပါတယ်။ Task တစ်ခုကို နောက်ပိုင်း ပြန်ညွှန်းဖို့ (command၊ URL၊ database row) မပြောင်းတဲ့ id လိုပါတယ်။ ဒါ့အပြင် id counter (next_id) ကိုပါ သိမ်းထားမှ reload ပြီးနောက် ဖျက်ပြီးသား id ကို ပြန်မသုံးမိမှာပါ။
Core concept: domain၊ storage၊ presentation
သေးငယ်တဲ့ app မှာတောင် "ဘာကို သိမ်းမလဲ"၊ "ဘယ်လို ပြောင်းလဲခွင့်ရှိလဲ"၊ "ဘယ်မှာ သိမ်းမလဲ"၊ "ဘယ်လို ပြမလဲ" ဆိုတဲ့ မေးခွန်းတွေကို code ရဲ့ သီးခြားနေရာတွေမှာ ဖြေရင် ပြင်ရလွယ်ပါတယ်။ ဒီ project ရဲ့ ဖွဲ့စည်းပုံက အောက်ပါအတိုင်းပါ။
| အလွှာ | ဒီ project မှာ | ဘာကို မသိရဘူးလဲ |
|---|---|---|
| Domain | Todo၊ TodoList၊ TodoError | File၊ JSON၊ print()၊ input() |
| Storage | save()၊ load() | Screen ပေါ် ဘယ်လိုပြမလဲ |
| Presentation | show()၊ နောက်ပိုင်း CLI/GUI | Data ကို ဘယ်မှာ သိမ်းလဲ |
၁။ State ကို ရှင်းရှင်း model လုပ်ပါ
@dataclass Todo မှာ id၊ text၊ done ဆိုတဲ့ field သုံးခု ပါပါတယ်။ Dataclass က __init__ နဲ့ __repr__ ကို အလိုလို ရေးပေးပြီး asdict() နဲ့ dict ပြောင်းလို့ JSON သိမ်းရ လွယ်ပါတယ်။ String တစ်ခုတည်း သိမ်းတာထက် field အသစ် (ဥပမာ due_date) ထည့်ရတာလည်း ပိုလွယ်ပါတယ်။
၂။ ပြောင်းလဲမှုတိုင်းကို method တစ်ခုစီ ပေးပါ
add()၊ toggle()၊ delete() က state ပြောင်းနိုင်တဲ့ တစ်ခုတည်းသော လမ်းကြောင်းတွေပါ။ add() က ဗလာ text ကို ငြင်းပြီး id ကို next_id ကနေ ပေးပါတယ်။ toggle() နဲ့ delete() က find() နဲ့ id ကို ရှာပြီး မတွေ့ရင် TodoError ကို raise လုပ်ပါတယ်။ စည်းကမ်းတွေ နေရာတစ်ခုတည်းမှာ ရှိလို့ CLI ဖြစ်ဖြစ် web ဖြစ်ဖြစ် အတူတူ လိုက်နာပါတယ်။
၃။ Storage ကို adapter အဖြစ် အပြင်မှာ ထားပါ
save() နဲ့ load() က TodoList ကို JSON နဲ့ ပြောင်းပေးရုံပါ။ next_id ကိုပါ သိမ်းလို့ reload ပြီးနောက် id 4 ကနေ ဆက်ပါတယ်။ ဖျက်ပြီးသား id 2 ကို ပြန်မသုံးပါဘူး။ နောက်ပိုင်း SQLite ကို ပြောင်းချင်ရင် ဒီ function နှစ်ခုကိုပဲ ပြန်ရေးရပါတယ်။
၄။ Atomic save
File ကို တိုက်ရိုက် "w" mode နဲ့ ဖွင့်လိုက်တာနဲ့ အဟောင်းက ဗလာ ဖြစ်သွားပါတယ်။ ရေးနေတုန်း crash ဖြစ်ရင် data ပျောက်ပါတယ်။ ဒါကြောင့် todos.json.tmp ထဲ အရင်ရေးပြီးမှ os.replace() နဲ့ နာမည်ပြောင်းပါတယ်။ os.replace() က တူညီတဲ့ filesystem ပေါ်မှာ atomic ဖြစ်လို့ file အဟောင်း ဒါမှမဟုတ် အသစ် တစ်ခုခုကိုပဲ မြင်ရပြီး တစ်ဝက်တစ်ပျက် file ကို ဘယ်တော့မှ မမြင်ရပါဘူး။
- load() က file ကို TodoList ပြောင်း
- Method တွေက id နဲ့ task ကို ပြောင်း
- save() က temp file ရေးပြီး replace
- show() က လက်ရှိ state ကို ပြ
User ကို ပြတဲ့ နံပါတ်က id ဖြစ်ရမယ်၊ list index မဖြစ်ရပါဘူး။ ဒါမှ sort လုပ်ပြီးပြီးချင်း command တွေ မှန်နေမှာပါ။
အခြေခံ ပုံစံ
@dataclass
class Item:
id: int
... # the fields you need
class Store: # domain: rules + stable ids
def add(self, ...) -> Item: ...
def change(self, item_id: int, ...) -> Item: ...
def save(store, path): ... # write tmp, then os.replace()
def load(path) -> Store: ... # missing file -> empty StoreDataclass နဲ့ data shape ကို သတ်မှတ်၊ domain class က id နဲ့ စည်းကမ်းတွေကို ကိုင်ပြီး save/load က storage ကို သီးခြား ကိုင်ပါတယ်။
ဥပမာ: model၊ storage နဲ့ reload စမ်းသပ်ချက်
Demo က "Learn Python" နဲ့ "Build To-Do App" ဆိုတဲ့ sample task နှစ်ခုကို သုံးပြီး app ကို အလွှာသုံးလွှာနဲ့ တည်ဆောက်ထားပါတယ်။ Demo က tempfile.TemporaryDirectory() ထဲမှာ run လို့ သင့် folder ထဲ tasks.txt မကျန်ခဲ့ပါဘူး။ ရှိပြီးသား file ကြောင့် run တိုင်း ရလဒ်ပြောင်းတာလည်း မဖြစ်ပါဘူး။ Save ပြီး reload လုပ်ကာ id တွေ၊ done status နဲ့ next_id ကျန်မကျန် စစ်ပါတယ်။
import json
import os
import tempfile
from dataclasses import asdict, dataclass
# ===== 1. Domain model: stable ids, not list positions =====
class TodoError(Exception):
"""A request the to-do list cannot carry out."""
@dataclass
class Todo:
id: int
text: str
done: bool = False
class TodoList:
def __init__(self, todos: list[Todo] | None = None, next_id: int = 1):
self.todos = todos or []
self.next_id = next_id
def add(self, text: str) -> Todo:
text = text.strip()
if not text:
raise TodoError("a task needs some text")
todo = Todo(self.next_id, text)
self.next_id += 1
self.todos.append(todo)
return todo
def find(self, todo_id: int) -> Todo:
for todo in self.todos:
if todo.id == todo_id:
return todo
raise TodoError(f"no task with id {todo_id}")
def toggle(self, todo_id: int) -> Todo:
todo = self.find(todo_id)
todo.done = not todo.done
return todo
def delete(self, todo_id: int) -> Todo:
todo = self.find(todo_id)
self.todos.remove(todo)
return todo
def pending(self) -> list[Todo]:
return [t for t in self.todos if not t.done]
# ===== 2. Storage adapter: JSON file with an atomic save =====
def save(todo_list: TodoList, path: str) -> None:
data = {"next_id": todo_list.next_id,
"todos": [asdict(t) for t in todo_list.todos]}
tmp_path = path + ".tmp"
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
os.replace(tmp_path, path) # readers see the old file or the new one
def load(path: str) -> TodoList:
if not os.path.exists(path):
return TodoList()
with open(path, encoding="utf-8") as f:
data = json.load(f)
return TodoList([Todo(**t) for t in data["todos"]], data["next_id"])
# ===== 3. Presentation =====
def show(todo_list: TodoList) -> None:
for t in todo_list.todos:
print(f" [{'x' if t.done else ' '}] #{t.id} {t.text}")
# ===== 4. Demo in a throwaway folder (no input() needed) =====
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "todos.json")
todos = load(path) # no file yet -> empty list
todos.add("Learn Python")
todos.add("Build To-Do App")
todos.add("Write tests")
todos.toggle(1)
todos.delete(2)
save(todos, path)
reloaded = load(path)
print("After reload:")
show(reloaded)
print(f"Pending: {[t.text for t in reloaded.pending()]}")
print(f"New task gets id {reloaded.add('Deploy').id}")
try:
reloaded.toggle(2)
except TodoError as error:
print(f"Error: {error}")Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Data shape as a dataclass
done: bool = FalseDefault value ပါတဲ့ field ဖြစ်လို့ Todo(1, "Learn Python") လို့ ဆောက်ရင် done က False ဖြစ်ပါတယ်။ Default ပါတဲ့ field တွေက default မပါတဲ့ field တွေ နောက်မှာ ရှိရပါမယ်။
- Ids come from a counter
self.next_id += 1id ကို len(self.todos) + 1 နဲ့ မတွက်ပါဘူး။ Task ဖျက်ပြီးရင် length လျော့သွားလို့ id ထပ်နိုင်ပါတယ်။ Counter က အမြဲ တက်ပဲ တက်ပါတယ်။
- Lookup by id, not index
raise TodoError(f"no task with id {todo_id}")find() က id တူတဲ့ task ကို ရှာပြီး မတွေ့ရင် IndexError လို မရှင်းတဲ့ error မဟုတ်ဘဲ domain error ကို raise လုပ်ပါတယ်။ Demo ရဲ့ နောက်ဆုံး line က ဖျက်ပြီးသား id 2 အတွက် ဒီ error ကို ပြပါတယ်။
- Atomic replace
os.replace(tmp_path, path) # readers see the old file or the new oneTemp file ကို အပြည့်ရေးပြီးမှ နာမည်ပြောင်းလို့ ရေးနေတုန်း crash ဖြစ်ရင်လည်း todos.json အဟောင်းက မပျက်ပါဘူး။ Windows မှာလည်း ရှိပြီးသား file ကို overwrite လုပ်ပေးပါတယ်။
- Rebuild objects on load
return TodoList([Todo(**t) for t in data["todos"]], data["next_id"])JSON ကနေ dict တွေ ပြန်ရပြီး Todo(**t) က dict key တွေကို keyword argument အဖြစ် ပေးပါတယ်။ next_id ကိုပါ ပြန်ယူလို့ reload ပြီးနောက် "Deploy" က id 4 ရပါတယ်၊ 3 ပြန်မရပါဘူး။
After reload:
[x] #1 Learn Python
[ ] #3 Write tests
Pending: ['Write tests']
New task gets id 4
Error: no task with id 2Corrupted file နဲ့ concurrent write
User က todos.json ကို text editor နဲ့ ပြင်ရင်း comma တစ်ခု ကျန်ခဲ့ရင် json.load() က json.JSONDecodeError ကို raise လုပ်ပါတယ်။ App က crash မဖြစ်သင့်သလို file ကို ဗလာနဲ့ overwrite လုပ်ပြီး data ဖျက်ပစ်တာလည်း မဖြစ်သင့်ပါဘူး။ ကောင်းတဲ့နည်းက error ကို ဖမ်းပြီး file ကို todos.json.broken အဖြစ် နာမည်ပြောင်းထားကာ user ကို အသိပေးတာပါ။
Terminal နှစ်ခုကနေ app ကို တပြိုင်နက် run ရင် နှစ်ခုစလုံးက file ကို load လုပ်၊ ကိုယ့်ပြောင်းလဲမှုကို ထည့်၊ save လုပ်ပါတယ်။ နောက်မှ save လုပ်တဲ့သူက ပထမလူရဲ့ ပြောင်းလဲမှုကို ဖျက်ပစ်ပါတယ် (lost update)။ JSON file အတွက် ဒါကို လက်ခံနိုင်ပေမဲ့ user အများ သုံးမယ်ဆိုရင် transaction ပါတဲ့ SQLite လို database ကို ပြောင်းသုံးပါ။
Domain ကို storage မပါဘဲ test လုပ်ပါ
TodoList က file ကို မသိလို့ todos = TodoList(); todos.add("x"); assert todos.find(1).text == "x" လို test တွေက disk ကို မထိဘဲ millisecond အနည်းငယ်နဲ့ ပြီးပါတယ်။ Storage test တွေကိုတော့ demo လို temporary directory ထဲမှာ run ပါ။
လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
Todo app က သင်ခန်းစာ project တစ်ခုပေမဲ့ ဒီဖွဲ့စည်းပုံက issue tracker၊ shopping cart၊ note app၊ booking system တွေမှာ အတူတူပါပဲ။ Record တိုင်းမှာ stable id ရှိပြီး URL (/tasks/42)၊ API request နဲ့ database foreign key တွေက အဲဒီ id ကိုပဲ ညွှန်းပါတယ်။ Production မှာ integer counter အစား UUID ကို သုံးတာ များပါတယ်။ Device နှစ်ခုက offline ဖြစ်နေရင်းတောင် id မတိုက်ဘဲ record ဆောက်နိုင်လို့ပါ။
Team တွေက domain function တွေကို unit test နဲ့၊ storage ကို temp directory ထဲမှာ integration test နဲ့ စစ်ပါတယ်။ Test case တွေထဲမှာ reload ပြီးနောက် data ကျန်မကျန်၊ text တူတဲ့ task နှစ်ခု (id မတူလို့ ခွင့်ပြုရမယ်)၊ မရှိတဲ့ id ကို ဖျက်တာ၊ save မအောင်မြင်တဲ့အခါ file အဟောင်း မပျက်တာ စတာတွေ ပါပါတယ်။
အမှားများ
ဖြစ်လေ့ရှိတဲ့ အမှားများ
id ကို len(list) + 1 နဲ့ တွက်တာ
Task သုံးခုထဲက #2 ကို ဖျက်ပြီး task အသစ်ထည့်ရင် len + 1 က 3 ဖြစ်လို့ ရှိပြီးသား #3 နဲ့ id ထပ်ပါတယ်။ ပြီးရင် "delete 3" က ဘယ် task ကို ဖျက်မလဲ မသေချာတော့ပါဘူး။ next_id counter ကို သုံးပြီး file ထဲမှာပါ သိမ်းပါ။
Domain method ထဲမှာ save() ဒါမှမဟုတ် print() ခေါ်တာ
add() ထဲမှာ file ရေးရင် test တိုင်းက disk ကို ထိပြီး နှေးကွေးလာပါတယ်။ Task တစ်ရာ import လုပ်ရင်လည်း file ကို တစ်ရာခါ ရေးပါတယ်။ print() ပါရင် GUI version မှာ terminal ထဲ စာတွေ ထွက်နေပါမယ်။ Method က state ကို ပြောင်းပြီး ရလဒ်ကို return ပြန်ရုံပဲ လုပ်ပါ။ Save နဲ့ display ကို ခေါ်တဲ့ဘက်က ဆုံးဖြတ်ပါ။
Load မအောင်မြင်ရင် ဗလာ list နဲ့ overwrite လုပ်တာ
except Exception: return TodoList() လို့ ရေးထားရင် JSON ပျက်နေတဲ့အခါ app က ဗလာ list နဲ့ စပြီး နောက် save မှာ user ရဲ့ task အားလုံးကို ဖျက်ပစ်ပါတယ်။ File မရှိတာ (ပထမဆုံး run) နဲ့ file ပျက်နေတာကို ခွဲပြီး ကိုင်တွယ်ပါ။
Mini challenge
Command handler ရေးပါ
Text command တစ်ကြောင်းကို လက်ခံပြီး TodoList ကို ပြောင်းကာ ပြမယ့် message ကို return ပြန်တဲ့ handle() function ကို ရေးပါ။ input() မသုံးဘဲ command list တစ်ခုကို loop ပတ်ပြီး စမ်းပါ။
- add <text>၊ done <id>၊ del <id>၊ list၊ clear-done command တွေကို ထောက်ပံ့ရပါမယ်
- id မဟုတ်တဲ့ argument ("two") နဲ့ မရှိတဲ့ id (9) အတွက် TodoError ကို raise လုပ်ရပါမယ်
- clear-done က ပြီးသွားတဲ့ task ဘယ်နှစ်ခု ဖယ်လိုက်လဲ ပြောရပါမယ်
- မသိတဲ့ command အတွက် TodoError ဖြစ်ရပြီး loop က error message ကို ပြကာ ဆက်သွားရပါမယ်
# Paste Todo, TodoList (with add and find) and TodoError from the lesson here.
def parse_id(arg: str) -> int:
# TODO: digits only -> int, otherwise TodoError("'two' is not a task id")
...
def handle(todos: "TodoList", line: str) -> str:
"""Run one command and return the message to show."""
command, _, arg = line.strip().partition(" ")
# TODO: add <text> -> "Added #1: Buy milk"
# TODO: done <id> -> "Completed #1"
# TODO: del <id> -> "Deleted #1"
# TODO: list -> one "[x] #1 text" line per task, or "(no tasks)"
# TODO: clear-done -> "Removed 1 finished task(s)"
# TODO: anything else -> raise TodoError
...
commands = ["add Buy milk", "add Call Mya", "add", "done 1", "del two",
"del 9", "add Pay rent", "list", "clear-done", "list", "undo"]
# TODO: run each command, print "> command" and then the result or "Error: ..."ရလဒ်: Task #1၊ #2 ထည့်ပြီး ဗလာ add၊ "two"၊ id 9 တို့အတွက် error သုံးခု ပြပါမယ်။ ပထမ list မှာ [x] #1 ပါပြီး clear-done က task 1 ခု ဖယ်ကြောင်း ပြောပါမယ်။ ဒုတိယ list မှာ #2 နဲ့ #3 ပဲ ကျန်ပြီး undo က unknown command error ဖြစ်ပါမယ်။
အရိပ်အမြွက် ကြည့်ရန်
str.partition(" ") က ပထမ space မှာ တစ်ခါပဲ ခွဲလို့ "add Buy milk" ကနေ command "add" နဲ့ arg "Buy milk" ရပါတယ်။ arg.isdigit() နဲ့ id ကို စစ်ပါ။
အဖြေ ကြည့်ရန်
from dataclasses import dataclass
class TodoError(Exception):
pass
@dataclass
class Todo:
id: int
text: str
done: bool = False
class TodoList:
def __init__(self) -> None:
self.todos: list[Todo] = []
self.next_id = 1
def add(self, text: str) -> Todo:
if not text.strip():
raise TodoError("a task needs some text")
todo = Todo(self.next_id, text.strip())
self.next_id += 1
self.todos.append(todo)
return todo
def find(self, todo_id: int) -> Todo:
for todo in self.todos:
if todo.id == todo_id:
return todo
raise TodoError(f"no task with id {todo_id}")
def parse_id(arg: str) -> int:
if not arg.isdigit():
raise TodoError(f"'{arg}' is not a task id")
return int(arg)
def handle(todos: TodoList, line: str) -> str:
"""Run one command and return the message to show."""
command, _, arg = line.strip().partition(" ")
if command == "add":
todo = todos.add(arg)
return f"Added #{todo.id}: {todo.text}"
if command == "done":
todo = todos.find(parse_id(arg))
todo.done = True
return f"Completed #{todo.id}"
if command == "del":
todo = todos.find(parse_id(arg))
todos.todos.remove(todo)
return f"Deleted #{todo.id}"
if command == "list":
rows = [f"[{'x' if t.done else ' '}] #{t.id} {t.text}" for t in todos.todos]
return "\n".join(rows) or "(no tasks)"
if command == "clear-done":
before = len(todos.todos)
todos.todos = [t for t in todos.todos if not t.done]
return f"Removed {before - len(todos.todos)} finished task(s)"
raise TodoError(f"unknown command '{command}'")
commands = ["add Buy milk", "add Call Mya", "add", "done 1", "del two",
"del 9", "add Pay rent", "list", "clear-done", "list", "undo"]
todos = TodoList()
for line in commands:
print(f"> {line}")
try:
print(handle(todos, line))
except TodoError as error:
print(f"Error: {error}")Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Task တွေကို list position နဲ့ မညွှန်းဘဲ မပြောင်းတဲ့ id နဲ့ ညွှန်းပြီး next_id ကိုပါ သိမ်းပါ
- @dataclass နဲ့ data shape ကို သတ်မှတ်ပြီး state ပြောင်းလဲမှုတိုင်းကို domain method တစ်ခုစီ ပေးပါ
- Storage ကို save()/load() adapter အဖြစ် သီးခြားထားပြီး temp file + os.replace() နဲ့ atomic save လုပ်ပါ
- Domain logic က input()၊ print()၊ file ကို မသိရဘဲ ဒါမှ keyboard နဲ့ disk မပါဘဲ test လုပ်လို့ရပါတယ်
The Python Tutorial — Python Software Foundation