งูต้นฉบับอ่านป้ายชนิดไฟล์ที่ติดมากับตะกร้า directory scan ขณะนาฬิกาทรายเตือนว่าป้ายอาจเก่า

Python 3.14 Path.info: ใช้ type cache จาก directory scan โดยไม่เผลอเชื่อข้อมูลเก่า

พี่โชว์Engineering

การเดิน directory แล้วถามทุก entry ว่าเป็นไฟล์หรือโฟลเดอร์อาจทำ system call ซ้ำ Python 3.14 เพิ่ม Path.info ซึ่งเป็น PathInfo พร้อม cache คำตอบเรื่องชนิดไฟล์ และ Path.iterdir() อาจเตรียมข้อมูลนี้จาก directory scan ให้แต่ละ Path อยู่แล้วครับ

import tempfile
import unittest
from pathlib import Path


def classify(root: Path) -> dict[str, str]:
    result = {}
    for entry in root.iterdir():
        if entry.info.is_dir():
            result[entry.name] = "directory"
        elif entry.info.is_file():
            result[entry.name] = "file"
        else:
            result[entry.name] = "other"
    return result


class PathInfoTests(unittest.TestCase):
    def test_classifies_entries_from_scan(self):
        with tempfile.TemporaryDirectory() as directory:
            root = Path(directory)
            (root / "notes.txt").write_text("hello", encoding="utf-8")
            (root / "assets").mkdir()
            self.assertEqual(
                classify(root),
                {"notes.txt": "file", "assets": "directory"},
            )


if __name__ == "__main__":
    unittest.main()

Cache ไม่ใช่ความจริงตลอดเวลา

Path.info เก็บคำตอบหลัง query และไม่มี API สำหรับ reset cache ถ้า filesystem เปลี่ยนระหว่างทาง ข้อมูลเดิมอาจไม่สะท้อนสถานะล่าสุด เอกสารแนะนำให้สร้าง Path object ใหม่เมื่อต้องการ info cache ใหม่ หรือเรียกเมธอดบน Path เช่น is_dir(), is_file() และ exists() เมื่อต้องการตรวจข้อมูลสดโดยไม่ใช้ cache นี้

ดังนั้นมันเหมาะกับงาน inventory ที่ยอมรับ snapshot ขณะ scan เช่นจัดกลุ่มไฟล์ก่อนประมวลผล แต่ไม่ควรใช้ตัดสินสิทธิ์หรือยืนยันว่า path ยังปลอดภัยก่อนเปิด เพราะมีช่องเวลาแบบ TOCTOU ระหว่างการตรวจและการใช้งาน สำหรับ security boundary ควรเปิด resource ด้วย primitive ที่เหมาะกับระบบปฏิบัติการ ตรวจ handle ที่เปิดแล้ว และหลีกเลี่ยงการเชื่อ path type จาก cache

เรื่อง symlink ก็ต้องกำหนดนโยบายให้ชัด PathInfo มีเมธอดหลายแบบ แต่การติดตาม link และ error จาก permission/filesystem อาจทำให้คำตอบต่างจาก intuition เทสต์กับ filesystem เป้าหมายและเก็บ error handling ไว้ใกล้จุดเปิดจริง

Recap

  • Path.info ใช้ข้อมูลจาก directory scan และ cache type query
  • เหมาะกับ snapshot/inventory ไม่ใช่ security check ที่ต้องสด
  • สร้าง Path ใหม่หรือเรียก is_*() เมื่อต้องการสถานะปัจจุบัน
  • เปิด resource แล้วตรวจ handle เมื่อ race มีผลต่อความปลอดภัยครับ