Like Stories? Love Python! šŸ“–šŸ Ep.1 - The One Ring (Singleton)

Published: (February 12, 2026 at 04:29 PM EST)
11 min read
Source: Dev.to

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:

ElementSingleton Analogy
ProtagonistThe Application (our hero’s journey begins here – trying to access a shared resource, facing the chaos of the digital realm)
Desire / ObjectiveReliable access to a single, consistent resource (database connection, configuration, logging system). The app wants convenience but needs consistency.
Antagonistic forceChaos from multiple competing instances – connection‑pool exhaustion, conflicting configurations, duplicate log files creating narrative entropy.
Central conflictThe 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 _initialized flag 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 truthWhen you actually need multiple instances (most of the time)
Logging systems – all footage goes to one editorWhen it makes testing harder (it usually does)
Caching layers – one prop warehouse, many retrievalsWhen 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

0 views
Back to Blog

Related posts

Read more Ā»

Python OOP for Java Developers

Converting a Simple Java Square Class to Python Below is a step‑by‑step conversion of a basic Square class written in Java into an equivalent Python implementa...