本文由 AI 分析生成
建立時間: 2026-03-28 來源: https://frostming.com/2025/singleton/
Summary
Frost argues that the Singleton pattern is unnecessary and commonly misimplemented in Python. The conclusion is blunt: you don’t need Singleton in Python; if you need shared state, use module-level variables. The article debunks four common Singleton implementations (decorator, class variable, metaclass, __new__) showing each has subtle problems, and explains why Python’s module system already provides a built-in singleton mechanism.
Frost 論證 Python 中 Singleton 模式既不必要又常被錯誤實現。結論直接:Python 不需要 Singleton,若需要共享狀態,使用模組級別變量即可。文章逐一分析四種常見 Singleton 實現的缺陷,並解釋 Python 的模組系統已內建了天然的單例機制。
Key Points
- In Python, module-level variables are singletons by nature — Python’s import system caches modules
- Decorator approach changes the type from class to function —
isinstance()checks break - Class variable approach requires careful
__init__handling to avoid re-initialization - Metaclass approach is overly complex for the problem
__new__approach still has re-initialization issues and is confusing- The real question is always: what interface should
MyClassexpose? Choose implementation based on the answer.
Insights
The meta-lesson is about pattern cargo-culting: developers interview-prep Singleton without understanding why it exists or whether the language already handles it. Python’s module system makes Singleton a solution in search of a problem. The broader principle — “consider how your code will be used and what interface you’re exposing” — applies beyond Singleton to all architectural choices.
Connections
Raw Excerpt
在 Python 中,你不需要 Singleton。如果需要,就用模块级别的变量。