29. Safer Alternatives to Pickle
Instead of pickle, use formats that are human-readable, portable, and safe.
Example
import json
from dataclasses import dataclass, asdict
@dataclass
class User:
name: str
age: int
user = User("alice", 30)
# 29. Serialize
with open("user.json", "w", encoding="utf-8") as f:
json.dump(asdict(user), f)
# 29. Deserialize
with open("user.json", "r", encoding="utf-8") as f:
data = json.load(f)
print(data)
✅ Lesson: Use json or dataclasses for structured, secure serialization.