Metaclasses & __new__: How Singletons Really Work

Metaclasses & __new__: How Singletons Really Work in Python: The Singleton pattern is easy to state — "one instance per class" — and easy to get subtly wrong.

Concept Explanation

The Singleton pattern is easy to state — "one instance per class" — and easy to get subtly wrong. The correct implementation requires understanding two things most tutorials skip: the difference between __new__ and __init__, and what a metaclass actually is.

Classes Are Objects

In Python, a class is itself an object, created at runtime like everything else. Its type is a metaclass.

class Foo:          # Foo is a Foo object
    pass

print(type(Foo))    # <class 'type'>
print(type(type))   # <class 'type'>

The default metaclass is type. When you write class Foo:, Python calls type.__call__(name, bases, namespace) to build the class. That is where class syntax actually goes.

__new__ vs __init__

__new__ is a static method that returns the object; __init__ then initialises that object. For normal classes you only write __init__. But __new__ runs first and is where an object is created — so it is the right place to decide whether to create one at all.

class Point:
    def __new__(cls, x, y):
        print(f"new: creating {cls.__name__}")
        obj = super().__new__(cls)      # actually allocate
        return obj                      # if you return None here, init is skipped

    def __init__(self, x, y):
        print(f"init: setting {x}, {y}")
        self.x, self.y = x, y

If __new__ returns an instance of the same class, __init__ runs. If it returns an instance of a different class, or None, __init__ is skipped entirely.

The Naive Singleton (Works, But Fragile)

class Settings:
    _instance = None
    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        self.debug = True

This passes a basic test (Settings() is Settings() is True) but has a flaw: __init__ runs on every call, so anything in it resets state each time you fetch the instance. The _instance guard only gates creation, not initialisation.

The Correct Singleton: A Metaclass

The clean fix keeps the instance logic out of the class body by putting it in the metaclass's __call__ — which is what runs at class instantiation time:

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]


class Config(metaclass=Singleton):   # inherits the behavior automatically
    def __init__(self):
        self.attempts = 0


a = Config()
b = Config()
print(a is b)          # True
a.attempts += 1
print(b.attempts)      # 1 -- same object, and __init__ ran only once

Why the difference matters: registration happens in __call__ before __init__ is invoked, so the second call returns the stored instance and never re-runs __init__.

When a Metaclass Is Worth It

Metaclasses are a power tool. The general rule: you want one when you need to intercept the creation of classes, not instances. The three legitimate uses:

UseWhat it does
SingletonEnforce one instance per class
RegistrationCollect all subclasses automatically (see the example)
Validation / auto-methodsGuarantee every subclass has a member, or inject one

Most "metaclass" code you meet is over-engineered. But ABCs (abstract base classes) use exactly this machinery, and abc is worth knowing.

ABCs: The Declarative Half

from abc import ABC, abstractmethod


class Shape(ABC):
    @abstractmethod
    def area(self) -> float: ...
    @abstractmethod
    def perimeter(self) -> float: ...


class Circle(Shape):
    def __init__(self, r): self.r = r
    def area(self): return 3.1416 * self.r ** 2
    def perimeter(self): return 2 * 3.1416 * self.r


shape = Circle(2)          # OK
# Shape() would raise: can't instantiate abstract class

A class with an unimplemented @abstractmethod cannot be instantiated, so the compiler of a statically-typed language does work that Python enforces at runtime instead.

Protocol: Structural, Not Inheritance

For a single method, typing.Protocol is often better than an ABC, because it does not require inheritance — it checks structure, not ancestry:

from typing import Protocol


class Drawable(Protocol):
    def draw(self) -> None: ...


class Canvas:                # no need to inherit Drawable
    def draw(self) -> None:
        print("drawing")


def render(item: Drawable) -> None:   # type checker only
    item.draw()

render(Canvas())    # Canvas has draw(), so it satisfies the Protocol

Protocols are the "duck typing, but documented" approach: if it quacks, it counts — and the type checker can see it.


Code Example #1 (Basic)

The three Singleton variants side by side, showing where each breaks.

# --- Variant A: __new__ with a reset flaw ---
class SettingsNew:
    _instance = None
    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    def __init__(self):
        self.debug = True
        self.count = 0


a = SettingsNew()
a.count = 99
b = SettingsNew()
print(f"A: __new__ singleton: same object = {a is b}, but count reset to {b.count}")
print("   -> __init__ ran on the second call, wiping the state you set\n")


# --- Variant B: metaclass, __init__ runs once ---
class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]


class Config(metaclass=Singleton):
    def __init__(self):
        self.count = 0
        self.debug = True


x = Config()
x.count = 99
y = Config()
print(f"B: metaclass singleton: same object = {x is y}, count preserved = {y.count}")
print("   -> __call__ guards before __init__, so state survives\n")


# --- Variant C: module level. A Python module is already a singleton. ---
print("C: a module object is created once per import -- the simplest 'singleton'.")
print("   Put the config in a .py file and import it; every importer shares it.")


# --- The metaclass approach also works across subclasses simultaneously ---
class LoggerSingleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]


class AppLogger(metaclass=LoggerSingleton):
    def log(self, msg): print(f"[app] {msg}")


class AuditLogger(metaclass=LoggerSingleton):
    def log(self, msg): print(f"[audit] {msg}")


print(f"D: AppLogger() is AppLogger()   = {AppLogger() is AppLogger()}")
print(f"   but AppLogger() is AuditLogger() = {AppLogger() is AuditLogger()}")
print("   -> the singleton is per-class, not per-metaclass\n")


# --- Thread-safety note ---
import threading

class SafeSingleton(type):
    """The same idea, but correct when two threads race to create the instance."""
    _instances = {}
    _lock = threading.Lock()
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:            # fast path, no lock
            with cls._lock:
                if cls not in cls._instances:   # re-check under the lock
                    cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]


class Connection(metaclass=SafeSingleton):
    def __init__(self):
        self.id = 1


print("E: without a lock, two threads can both see 'no instance yet' and both")
print("   build one. The double-checked lock above closes that window.")
print(f"   Connection() is Connection() = {Connection() is Connection()}")

The comparison that matters is A vs B. Variant A looks right in a tutorial and loses data in practice; variant B avoids it by construction.

Code Example #2 (Intermediate)

A metaclass that registers subclasses, plus an ABC and a Protocol.

import time
from abc import ABC, abstractmethod
from typing import Protocol


# ---------- Metaclass for automatic registration ----------
class Registry(type):
    """Every subclass of a Registry-based class registers itself on creation."""
    def __init__(cls, name, bases, namespace):
        super().__init__(name, bases, namespace)
        if not bases:                   # the base class itself
            cls._registry = []
        else:
            cls._registry.append(cls)   # each subclass appends itself


class Plugin(metaclass=Registry):
    """Base for all plugin classes. Subclasses register automatically."""

    def run(self):
        raise NotImplementedError


class CleanupPlugin(Plugin):
    def run(self):
        print("  cleaning old temp files")


class BackupPlugin(Plugin):
    def run(self):
        print("  backing up the database")


print("Registered plugins (the metaclass did this -- no manual list):")
for plugin_cls in Plugin._registry:
    print(f"  {plugin_cls.__name__}")
print("  Every subclass appended itself at class-creation time, which is why")
print("  a metaclass beats a decorator here: it also catches subclasses")
print("  written later, in other files, by other people.\n")

print("Running them all:")
for plugin_cls in Plugin._registry:
    plugin_cls().run()
print()


# ---------- ABC as an enforceable interface ----------
class Notifier(ABC):
    @abstractmethod
    def send(self, message: str) -> None:
        """Deliver a message. Every subclass must implement this."""

    def send_many(self, messages: list[str]) -> None:
        for m in messages:
            self.send(m)


class EmailNotifier(Notifier):
    def send(self, message: str) -> None:
        print(f"  [email] {message}")


class SmsNotifier(Notifier):
    def send(self, message: str) -> None:
        print(f"  [sms]   {message}")


class BadNotifier(Notifier):
    pass            # forgot send() -> cannot instantiate


print("ABC enforcement:")
n = EmailNotifier()
n.send_many(["hello", "world"])
try:
    BadNotifier()
except TypeError as exc:
    print(f"  BadNotifier() raised: {str(exc)[:48]}...\n")


# ---------- Protocol: structural typing without inheritance ----------
class SupportsFmt(Protocol):
    def format(self, spec: str = "") -> str: ...


class Color:
    def __init__(self, name, code):
        self.name, self.code = name, code
    def format(self, spec=""):
        return f"{self.name} (ansi {self.code})" if spec == "ansi" else self.name


class City:
    def __init__(self, name):
        self.name = name
    # no format() method -> does NOT satisfy SupportsFmt

def display(item: SupportsFmt) -> str:
    return item.format()


print("Protocol (structural) typing:")
print(f"  Color has format() -> {display(Color('green', '32'))}")
try:
    display(City("Paris"))
except AttributeError:
    print("  City has no format() -> rejected at call time")
print("  A type checker flags the City call statically; at runtime you get")
print("  an AttributeError. Protocol is a checker construct, not a guard.\n")


# ---------- Class decorator vs metaclass for injection ----------
def timed(cls):
    """Class decorator: wrap every method with a timer."""
    for name, member in list(cls.__dict__.items()):
        if callable(member) and not name.startswith("__"):
            def make_wrapper(fn, nname=name):
                def wrapper(self, *args, **kwargs):
                    start = time.perf_counter()
                    result = fn(self, *args, **kwargs)
                    dur = (time.perf_counter() - start) * 1000
                    print(f"    [{nname}] {dur:.2f} ms")
                    return result
                return wrapper
            setattr(cls, name, make_wrapper(member))
    return cls


@timed
class Worker:
    def fetch(self):
        time.sleep(0.05)
        return "data"
    def compute(self):
        time.sleep(0.02)
        return 42


print("Class decorator injecting timing (often simpler than a metaclass):")
w = Worker()
w.fetch()
w.compute()

print("\nTwo tools, same job: a metaclass controls class creation; a class")
print("decorator post-processes an already-built class. Prefer the decorator")
print("unless you need the behaviour on subclasses you haven't written yet.")

There is a genuine overlap between the points. The timed decorator and the Registry metaclass both serve one purpose — add behaviour to classes — but the metaclass also catches future subclasses, which the decorator cannot.


Common Mistakes

  1. Using __new__ when __init__ is enough: __new__ is for controlling allocation, not for setting attributes.
  2. Calling super().__init__ after returning a foreign object in __new__: if __new__ returns an instance not of cls, Python still tries to call __init__ and raises.
  3. A Singleton whose __init__ re-runs every call: the naive __new__ example. Use the metaclass form.
  4. Basing singleton state on the instance but testing with is: two different singleton implementations can look equal while remaining separate (per-thread, per-mixin, etc.).
  5. Using a metaclass where a class decorator would do: over-engineering for a one-off.
  6. Ignoring thread-safety: two threads can both create the instance in the same instant. Add threading.Lock.
  7. Keeping mutable state in the class, not the instance: a metaclass singleton with instance state is fine; a class-level mutable list can be shared by accident.
  8. Forgetting cls._instances is keyed by class: with subclasses you may end up with multiple singletons. Check whether you intended a single instance across the hierarchy.
  9. Testing ABCs by instantiating: you cannot; that is the point. Check with issubclass instead.
  10. Using Protocol when you want an interface you can rely on at runtime: Protocol is a type-checker construct. Use an ABC for runtime checks.

Best Practices

  • Prefer a module as a singleton: import the module and call its functions; Python guarantees single execution of the module body.
  • If you need a class, use the metaclass form — it correctly gates __init__.
  • Use typing.Protocol for structural interfaces, and an ABC when you want runtime enforcement and subclass registration.
  • Use a classmethod or a @classmethod-wrapped get_instance over magic if the team is new to the concept.
  • Reach for a class decorator before a metaclass. In most cases it is sufficient and easier to read.
  • Guard shared caches behind a threading.Lock if your service is concurrent.
  • Never use the __new__ two-step to implement a Singleton when the metaclass version is available; it's a common point of failure.
  • Document the choice: singletons and metaclasses surprise readers. State why the pattern is there.

Practice Exercises

  1. The Naive vs Correct: Write the __new__-based Singleton from the lesson, set a state attribute, fetch the instance a second time, and show the attribute is reset. Then rewrite with the metaclass form and demonstrate the state looks good on the second fetch.
  2. The Registry: Define a Registry metaclass that auto-registers every subclass. Define three plugin classes and print the registry. Comment on why a metaclass is a fit (future subclasses you haven't written yet).
  3. ABC vs Protocol: Build a class hierarchy with an ABC and the same interface with a Protocol. Instantiate both, and write a comment on the trade-off (runtime enforcement vs structural flexibility).