Like Stories? Love Python! šš Ep.1 - The One Ring (Singleton)
Source: Dev.to
EpisodeāÆ1: The One Ring (Singleton Pattern)
Accompanying sourceācode repository:
Learning Python ObjectāOriented
Listen, folks. Pull up a chair. Let me tell you a story about the most powerful pattern in all of programming ā and Iām going to tell it the way stories areāÆMEANT to be told.
The OneāLine Logline
āEnsure only one instance of a class exists, no matter how many times someone tries to create it.ā
Think of it as the highlander pattern ā there can be only one! This is your high concept, the pitch that gets the greenālight from the Python interpreter.
The Short Story (The Elevator Pitch)
Picture this: a kingdomās ancient vault contains only one Master Key that opens all doors. Guards may come and go, requesting āthe key,ā but the vault keeper ā our gatekeeper character ā always hands them the same singular key, never a duplicate. If the key is already out, they wait. There is only ever one Master Key in existence.
Thatās your premise. Thatās your setup. Now let me show you the payoff.
The Fictional Match š¬
The One Ring from The Lord of the Rings: The Fellowship of the Ring
(IMDB: tt0120737)
Sauron didnāt craft twenty rings of power for maximum evil ā he made one. One ring to rule them all. Every character obsessing over it, fighting for it, questing for it ā Frodo, Gollum, Boromir, Saruman ā theyāre all after the same exact ring. Not a copy. Not RingāÆ#47. THE Ring.
PeterāÆJackson understood something profound when he adapted Tolkienās work: the MacGuffin ā Hitchcockās term, by the way ā isnāt just a ring. Itās THE ring, the irreplaceable object that drives the entire narrative engine. The unity of the artifact creates the unity of purpose across nine hours of cinematic storytelling.
Thatās Singleton energy right there, compressed into pure narrative gold. (Hopefully your database connection has better intentions than enslaving Middleāearth and corrupting hobbits.)
The visual metaphor is perfect: one ring, one dark lord, one object of power. Jackson even gives us that iconic closeāup shot ā the ring filling the frame, singular and terrible. THAT is production design serving story structure, my friends.
The RobertāÆMcKee Story Breakdown
If youāve read RobertāÆMcKeeās seminal work Story: Substance, Structure, Style, and the Principles of Screenwriting (and if you havenāt, close this tab right now and go get it ā Iāll wait), you know that every story is built on dramatic structure. McKee teaches us that story is about a protagonist pursuing an object of desire against antagonistic forces.
Letās break down the Singleton pattern using McKeeās story spine:
| Element | Singleton Analogy |
|---|---|
| Protagonist | The Application (our heroās journey begins here ā trying to access a shared resource, facing the chaos of the digital realm) |
| Desire / Objective | Reliable access to a single, consistent resource (database connection, configuration, logging system). The app wants convenience but needs consistency. |
| Antagonistic force | Chaos from multiple competing instances ā connectionāpool exhaustion, conflicting configurations, duplicate log files creating narrative entropy. |
| Central conflict | The gap between expectation and reality ā the tension between ājust create another one!ā convenience and the harsh truth that some things must be singular. This is the inciting incident. |
| Turning point (McKeeās Crisis Decision) | The moment the application realizes that getting āthe same objectā is fundamentally different from getting āa new object with the same values.ā This is the act break / revelation scene. |
| Resolution (the Climax) | All parts of the application share the one true instance harmoniously ā equilibrium restored, catharsis achieved. |
| Controlling idea (McKeeās thematic premise) | Unity is achieved through singularity ā some problems require a single source of truth, not multiple competing voices. This thematic statement echoes through the entire codeābase architecture. |
Every design pattern is a threeāact structure waiting to happen. The Singleton follows classical dramatic progression: setup (multiple instances cause problems), confrontation (we need only one), resolution (we enforce singularity). Itās Jaws for your database connection ā you donāt need multiple sharks; one perfect apex predator gets the job done.
RealāWorld Implementations (The Production Examples)
Youāve already seen this pattern in the production environment ā youāve probably used Singletons without realizing it. These are your practical applications, your proof of concept:
- Database connection pools ā you donāt want 500 connections; you want the connection manager.
- Configuration managers ā one source of truth for app settings.
- Logging systems ā all modules write to the logger, not their own separate logs.
- Cache managers ā one shared cache, not fragmented memory chaos.
- Thread pools ā one pool managing all workers.
- Application state ā single source for runtime state (e.g., Redux in Reactāland).
The Minimal Python Example (The VisualāEffects Sequence)
Okay, enough theory. Let me show you the money shot ā the transition from storyboard to actual footage.
Hereās a Singleton in its simplest form ā no CGI, no postāproduction magic, just pure practical effects:
class DatabaseConnection:
_instance = None # The "one ring" lives here ā our SINGULAR ARTIFACT
def __new__(cls, *args, **kwargs):
"""
Create a new instance only if one does not already exist.
Subsequent calls return the existing instance.
"""
if cls._instance is None:
cls._instance = super().__new__(cls)
# Perform any oneātime initialization here
cls._instance._initialize(*args, **kwargs)
return cls._instance
def _initialize(self, connection_string):
# Expensive setup (e.g., opening a DB socket) runs once
self.connection_string = connection_string
self._connect()
def _connect(self):
# Placeholder for real connection logic
print(f"Connecting to database at {self.connection_string}")
# Example method that would be used throughout the app
def query(self, sql):
print(f"Executing query: {sql}")
# Return mock result
return []
# Usage
if __name__ == "__main__":
db1 = DatabaseConnection("postgresql://localhost/db")
db2 = DatabaseConnection("postgresql://localhost/db")
# Both variables point to the same object
assert db1 is db2
db1.query("SELECT * FROM users;")
db2.query("SELECT * FROM orders;")
Running the script prints the connection message once, proving that only a single instance was created, even though we called the constructor twice.
Takeaway
The Singleton pattern is more than a ātechnical trick.ā Itās a narrative device that enforces unity through singularity, mirroring the timeless story structures that make great tales ā and great software ā unforgettable. Use it wisely, and let your code tell a clear, focused story.
The Singleton Pattern in Python ā A āBehindātheāScenesā Walkthrough
class DatabaseConnection:
"""
The __new__ method is called BEFORE __init__.
It's where Python creates the actual object.
Think of __new__ as your CASTING DIRECTOR.
We hijack it to ensure only ONE actor ever plays this role.
Every audition returns the SAME performer.
"""
_instance = None
def __new__(cls, *args, **kwargs):
"""
First time? This is the ORIGIN STORY.
"""
if cls._instance is None:
# Create the sole instance
cls._instance = super().__new__(cls)
cls._instance._initialized = False
# Return the SAME instance every time ā THE CONTINUITY
return cls._instance
def __init__(self):
"""
This still gets called each time, so we use a flag
to prevent reāinitialization.
Think of this as the actor's MAKEUP AND WARDROBE.
We only apply it once ā the first time they step on set.
"""
if self._initialized:
return # Already in costume ā we're good to go!
self._initialized = True
self.connection = "Connected to database"
print("š Database connection established!")
# The magic happens here ā THIS IS YOUR REVEAL MOMENT:
db1 = DatabaseConnection() # THE PROTAGONIST enters the scene
db2 = DatabaseConnection() # Wait⦠is this a different character?
print(db1 is db2) # True ā PLOT TWIST! Same character!
print(id(db1) == id(db2)) # True ā same actor, same memory address
# Both variables point to the SAME instance ā THE SHARED REALITY
db1.connection = "Modified connection"
print(db2.connection) # "Modified connection" ā CONTINUITY MAINTAINED!
š¬ The Directorās Commentary
__new__ is the gatekeeper ā your studio security guard.
It creates objects before __init__ runs (preāproduction).
- The first (and only) instance is stored in the class variable
_instanceā our master copy, the original negative. - Every subsequent call returns that same instance ā perfect continuity editing. No jump cuts, no mistakes.
- The
_initializedflag prevents reārunning initialization code ā we donāt reāshoot scenes weāve already captured.
ā When Should You Use a Singleton? (The GreenāLight Decision)
| ā Goodāfit scenarios | ā When to avoid |
|---|---|
| Database connection pools ā one director for the ensemble cast | āJust becauseā ā donāt use it for everything! |
| Configuration management ā the production bible, single source of truth | When you actually need multiple instances (most of the time) |
| Logging systems ā all footage goes to one editor | When it makes testing harder (it usually does) |
| Caching layers ā one prop warehouse, many retrievals | When shared global state will cause confusion |
| Hardware interface managers ā one printer driver, not ten |
š¦ The Pythonic Alternative: ModuleāLevel Singleton (The Indie Approach)
Hereās the secret the big studios donāt want you to know.
Python modules are already singletons. When you import a module, Python caches it, giving you builtāin continuity across your codebase.
# config.py ā This is your MASTER SCRIPT
class Config:
def __init__(self):
self.database_url = "postgresql://localhost/mydb"
self.debug_mode = True
# Create ONE instance at module level ā THE CANONICAL VERSION
config = Config()
# anywhere in your app ā EVERY SCENE references the same prop
from config import config
print(config.database_url) # Same object everywhere! CONTINUITY MAGIC!
No complex __new__ gymnastics, no elaborate rigging ā just simple, effective storytelling.
š The Plot Twist (The ThirdāAct Reversal)
Singletons are powerful but dangerous ā like the One Ring or the Ark of the Covenant. They introduce global state, make testing harder, and create hidden dependencies that can surface at the worst possible moment.
Modern Python applications often replace raw Singleton patterns with dependencyāinjection frameworks, but understanding the classic structure is still valuable:
- Legacy codebases still use singletons extensively.
- The concept of a single shared resource remains relevant even when the implementation changes.
- It teaches you how Pythonās objectācreation pipeline (
__new__ā__init__) works under the hood.
Use singletons wisely, and let Pythonās module system do the heavy lifting whenever possible.
Good (Understanding practical effects makes you appreciate digital magic)
This is your film education. This is your foundation.
šÆ Key Takeaways (The Trailer Moments)
- Singleton ensures only one instance of a class exists ā One ring to rule them all
- Use
__new__to intercept object creation ā your casting director, your gatekeeper - Perfect for shared resources ā database connections, configs, loggers ā the production essentials
- Python modules are natural singletons ā builtāin continuity, leverage the system
- āThere can be only oneā ā but that doesnāt mean there should be (choose your moments)
Great power, great responsibility ā this isnāt just SpiderāMan wisdom, itās core architectural philosophy.
- McKeeās story spine applies to code architecture ā protagonist, desire, antagonism, resolution
- Every pattern is a threeāact structure waiting to happen
š¬ Coming Up Next (The PostāCredits Tease)
In EpisodeāÆ2 weāll explore the Factory Pattern ā or, as I like to call it, āthe Sorting Hat of object creation.ā
Why decide what type of object to create when you can delegate that decision to something smarter? Itās like casting directors in Hollywood ā they donāt ask actors to cast themselves. Thereās a system, a process, a creative decisionāmaking framework.
Weāll talk about Harry Potter, character archetypes, and how factory methods mirror the heroās journey. Trust me on this one.
Stay tuned, folks. The best is yet to come.
Enjoying this series? Hit that ā¤ļø button ā itās like applauding at a premiere! Got thoughts, corrections, or better movie metaphors? The comments section below is your Q&A panel. If you have a favorite design pattern youād like to see explained through the lens of cinema, let me know ā Iām always looking for the next story arc!
Remember: code is storytelling. Every class is a character. Every method is a scene. Every design pattern is a narrative structure refined over decades of collective experience. Youāre not just writing code ā youāre crafting the next great epic.
Fade to black. Roll credits.
Further Reading (The Bonus Features)
-
Learning Python ObjectāOriented ā Design Patterns
ā the source material -
Robert McKee ā Story: Substance, Structure, Style, and the Principles of Screenwriting
ā the master text, required reading -
Gang of Four Design Patterns
ā the classic tome (heavy reading, but foundational ā like studying Citizen Kane) -
Pythonās
__new__vs__init__
ā official documentation on object creation (the technical manual) -
The Lord of the Rings: The Fellowship of the Ring on IMDb
ā the cinematic reference, a visual storytelling masterclass