def singleton(cls): instances = {} def getinstance(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return getinstance
Decorators & Metaclasses

Meaning

A decorator that ensures a class has only one instance, returning the same instance on every call.

Primary Function

Enforces the singleton design pattern by caching the first instantiated object per class and returning it on subsequent calls.

Communicative Purpose

Defines a reusable decorator that enforces singleton instantiation for any class it decorates.

Função primária

Enforces the singleton design pattern by caching the first instantiated object per class and returning it on subsequent calls.

Propósito comunicativo

Defines a reusable decorator that enforces singleton instantiation for any class it decorates.

Situações de gatilho

When a class should have exactly one instance throughout the program lifecycle, such as a configuration manager, logger, or connection pool.

Contextos

Used in software design where global state is needed but global variables are discouraged; common in configuration, caching, logging, and hardware abstraction layers.

Família do chunk

  • singleton pattern
  • factory pattern
  • dependency injection
  • monostate pattern

Upgrade path

Consider using metaclass-based singleton or module-level instance for thread‑safety and subclass safety.

Tag de espaçamento: Medium-term

Log in to save chunks.