All gists

tempfile 模組可用於建立臨時檔案或目錄,在程式執行期間存儲暫時資料,並確保在程式結束後自動清理,適用於 測試、快取、臨時儲存 等場景。

0 0 0 3
1 import tempfile
2 import os
3
4 with tempfile.TemporaryDirectory() as temp_dir:
5 pid = os.getpid() # 取得當前進程 ID
6 temp_file = os.path.join(temp_dir, f"process_{pid}.txt")
7
8 # 建立並寫入臨時檔案
9 with open(temp_file, "w") as f:
10 f.write(f"這是進程 {pid} 的臨時檔案")
Last active 7 hours ago debugging inspect introspection python reflection

inspect 模組允許在執行時動態獲取函式、類別、模組的結構與資訊,適用於 除錯、程式碼分析、自動文件生成、動態調試 等場景。

0 0 0 3
1 import inspect
2
3 def example_function(a: int, b: str = "default") -> bool:
4 """示範函式,回傳 True 或 False"""
5 return bool(a)
6
7 # 獲取函式參數
8 signature = inspect.signature(example_function)
9 print(f"函式簽名: {signature}")

pydantic 提供基於 Python 類別的數據驗證與解析功能,適用於 API 請求驗證、資料模型定義、設定管理 等場景。

0 0 0 3
1 from pydantic import BaseModel, Field, ValidationError
2
3 class User(BaseModel):
4 name: str = Field(..., title="使用者名稱", min_length=2)
5 age: int = Field(..., gt=0, le=150, description="年齡必須介於 1 到 150 之間")
6 email: str
7
8 # 測試資料
9 try:
10 user = User(name="Tim", age=30, email="tim@example.com")

importlib 允許在執行時動態載入模組,適用於 外部插件管理、模組熱加載、延遲載入以提升效能 等場景。

0 0 0 3
1 import importlib
2
3 # 動態載入內建模組
4 math_module = importlib.import_module("math")
5 print(math_module.sqrt(16)) # 4.0
6
7 # 動態載入自訂模組
8 module_name = "my_module" # 假設有 my_module.py
9 custom_module = importlib.import_module(module_name)
10 print(custom_module.hello()) # 假設 my_module 有 hello() 函式

functools 模組提供多種函式工具,如記憶化(lru_cache)、部分應用(partial)和函式包裝(wraps),適用於提升效能、簡化回呼函式與裝飾器開發。

0 0 0 3
1 import functools
2
3 @functools.lru_cache(maxsize=5)
4 def fibonacci(n):
5 """計算費氏數列(具備快取功能)"""
6 if n < 2:
7 return n
8 return fibonacci(n - 1) + fibonacci(n - 2)
9
10 print(fibonacci(10)) # 快速計算
Last active 7 hours ago abc abstract-class interface oop python

ABC(Abstract Base Class)允許定義抽象類別,強制子類別實作特定方法,適用於建立統一的介面規範,確保繼承的類別都遵守特定的行為。

0 0 0 1
1 from abc import ABC, abstractmethod
2
3 # 定義抽象類別
4 class Animal(ABC):
5 @abstractmethod
6 def make_sound(self) -> str:
7 """所有動物都必須實作此方法"""
8 pass
9
10 # 繼承並實作抽象方法

ThreadPoolExecutor 提供了一種簡單的方式來管理多執行緒,適用於 I/O 密集型任務(如網路請求、檔案處理、資料庫查詢),提高執行效率。

0 0 0 1
1 from concurrent.futures import ThreadPoolExecutor, as_completed
2 import time
3
4 def task(n):
5 """模擬一個耗時任務"""
6 time.sleep(n)
7 return f"Task {n} completed after {n} seconds"
8
9 # 建立執行緒池
10 with ThreadPoolExecutor(max_workers=3) as executor: