Pythonコードの表示テスト
本記事は、技術ブログにおける「ソースコードのシンタックスハイライト(色付け)」の見え方を確認するためのテスト用記事です。
1. 基本的なデータ処理クラス
まずは、Pythonの標準的なクラス定義や、型ヒント(Type Hinting)、デコレータなどがどのように色付けされるかの確認です。
from dataclasses import dataclass
from typing import List, Dict, Optional
import time
@dataclass
class UserActivity:
user_id: str
action_type: str
timestamp: float
metadata: Optional[Dict[str, str]] = None
class ActivityProcessor:
def __init__(self, batch_size: int = 100):
self.batch_size = batch_size
self.buffer: List[UserActivity] = []
def process_event(self, event: UserActivity) -> None:
"""
ユーザーのイベントログを受け取り、バッチサイズに達したら処理する
"""
self.buffer.append(event)
if len(self.buffer) >= self.batch_size:
self._flush_buffer()
def _flush_buffer(self) -> None:
print(f"[{time.time()}] Flushing {len(self.buffer)} events to database...")
# 擬似的なデータベース書き込み処理
self.buffer.clear()
if __name__ == "__main__":
processor = ActivityProcessor(batch_size=3)
processor.process_event(UserActivity("u-123", "login", time.time()))2. 非同期処理とジェネレータ
次に、async/awaitの構文や例外処理(try/except)、リスト内包表記がどのように見えるかの確認用コードです。
import asyncio
import random
async def fetch_data_from_api(endpoint: str) -> dict:
# ネットワーク通信をシミュレート
await asyncio.sleep(random.uniform(0.1, 0.5))
if random.random() < 0.1:
raise ConnectionError(f"Failed to connect to {endpoint}")
return {"status": 200, "data": f"Response from {endpoint}"}
async def main():
endpoints = [f"api/v1/resource/{i}" for i in range(5)]
# 複数のAPIリクエストを並列で実行し、結果を待つ
tasks = [fetch_data_from_api(ep) for ep in endpoints]
try:
results = await asyncio.gather(*tasks, return_exceptions=True)
for ep, result in zip(endpoints, results):
if isinstance(result, Exception):
print(f"Error on {ep}: {result}")
else:
print(f"Success on {ep}: {result['data']}")
except Exception as e:
print(f"Critical failure: {e}")
# Python 3.7+
# asyncio.run(main())
文字の太さや、予約語(class, def, asyncなど)の色合い、背景の黒さなどは見やすいでしょうか?