Python typing.override: แสตมป์บอก type checker ว่าตั้งใจทับเมธอดแม่
น้องกายEngineering
เคยสะกดชื่อเมธอดลูกผิดแล้ว type checker เงียบใช่ไหมครับ — ตั้งแต่ Python 3.12 มี typing.override (PEP 698) แปะบนเมธอดที่ตั้งใจทับของแม่
ประโยชน์:
- ถ้าชื่อ/ซิกเนเจอร์ไม่แมตช์แม่ เครื่องมืออย่าง mypy/pyright ฟ้อง
- อ่านโค้ดรู้ทันทีว่าเมธอดนี้ตั้งใจ override ไม่ใช่เมธอดใหม่บังเอิญ
- รันไทม์แทบไม่ทำอะไร — เป็นตัวช่วย typing เป็นหลัก
import unittest
from typing import override
class Base:
def label(self) -> str:
return "base"
class Child(Base):
@override
def label(self) -> str:
return "child"
class TestOverride(unittest.TestCase):
def test_runtime(self):
self.assertEqual(Child().label(), "child")
self.assertTrue(callable(override))
if __name__ == "__main__":
unittest.main()
Recap
- ใส่
@overrideทุกเมธอดที่ตั้งใจทับของแม่ในโค้ดใหม่ - เปิด type checker ใน CI — decorator อย่างเดียวไม่พอ
- อ่านdocs typing.override