Shared posts

23 Jan 17:06

Por Qué los Mejores Líderes NO Deciden Solos (Modelo de Contingencias Explicado). Vroom y Yetton

by Santiago Ávila Vila

¿Sabías que no existe un único estilo de liderazgo eficaz para todas las situaciones? En este video te explico el Modelo de las Contingencias de Vroom y Yetton y cómo decidir cuándo liderar de forma autoritaria o participativa para lograr mejores decisiones y mayor compromiso del equipo.
#Liderazgo #TomaDeDecisiones #VroomYYetton #GestiónDeEquipos #PsicologíaOrganizacional
23 Jan 17:06

La última generación capaz de generar riqueza antes de que la IA envíe al paro a los jóvenes.JL Cava

by Jose Luis Cava
23 Jan 17:06

Business Observability with Dynatrace | Danne Aguiar | SREday Campinas 2025 Q4

by SREday

SREday Campinas 2025 Q4 - December 4 2025
Grab your ticket for the next SREday: https://www.sreday.com
Upcoming SREday CFPs: https://cfp.ninja/?q=sreday&status=open

Chapters
00:00 Introduction to Observability and Business Outcomes
00:23 Meet Denny: Your Presenter
01:13 Understanding Business Observability
01:57 The Importance of Business Metrics
03:23 Golden Signals and Business Impact
04:29 Case Study: Travel Application Incident
06:33 Implementing Business KPIs
07:06 Capturing Data from Various Sources
10:23 Real-World Applications and Examples
14:26 Conclusion and Q&A
23 Jan 17:05

Temporal y bulos.

by El Camionero Acrata TEIS
23 Jan 17:04

La inventora de las estafas piramidales

by Carlos Lopez
Si hay algo deplorable en esta vida es que te quiten el mérito de lo que con tu sudor y esfuerzo has logrado. Esto ha sucedido a lo largo de la historia con infinidad de personas de todo tipo y pelaje. A veces con ilustres científicos, que han visto empañado su logro con la atribución ... Leer más
23 Jan 17:04

Canadá (re)descubre el Derecho internacional

by Ander Gutiérrez-Solana

Esta semana hemos asistido en Davos al discurso del primer ministro de Canadá, Mark Carney, considerado histórico por mucha prensa generalista, por ser certero en el análisis y un cierre del “viejo orden mundial basado en normas”. Un calificativo, el de histórico, algo exagerado pues Carney no propone cambios de fondo, aunque sí de alianzas.

Un discurso tan sincero como hipócrita

Honesto con la actualidad internacional, Carney ha sido también muy hipócrita. No ha reconocido que, lo que llama “viejo orden”, no es que ahora sea injusto, sino que las injusticias inherentes a él, ahora dañan a Canadá. De ahí su reclamo de un mundo basado en valores y normas, sin hegemonías. 

Estas llamadas al respeto del Derecho internacional significan dos cosas. Por una parte, que sigue gozando de un apoyo mayoritario en el imaginario, pues marca las líneas rojas que aseguran la coexistencia pacífica. Esas reglas, inspiradas en la Carta de la ONU, no han cambiado en 80 años. Ni en la Guerra Fría; ni en la posterior hegemonía de EE. UU., finalizada en 2003 con la ilícita invasión de Iraq; ni en este periodo de reconfiguración de los equilibrios, con dos superpotencias, China y EE. UU., y un reguero de potencias medias, como Rusia, la UE, Brasil, India o Sudáfrica.

En segundo lugar, que el nuevo orden mundial, el que fija el reparto de poder, se decidirá sobre las reglas clásicas del Derecho internacional. Los “órdenes mundiales” cambian porque son fruto de su momento histórico. Y ese cambio puede venir desde el derecho o contra él.  

Carney afirmaba que ahora “el orden basado en normas se está desvaneciendo, que los fuertes pueden hacer lo que pueden y los débiles deben sufrir lo que deben». Evidentemente, los débiles ya conocían esta realidad y no es nueva. El líder canadiense no ha reconocido la participación de su país en las injusticias, pero sí reconoce que “prosperó” bajo el mismo orden.   

Canadá ha participado, con EE. UU., en el genocidio en Gaza, colaborando con Israel; y en las guerras ilegales (por distintas razones) en Kosovo, Afganistán, Siria o Libia. Canadá, este mismo mes, no ha condenado la agresión a Venezuela. Carney reclama en su discurso el mantenimiento de los principios jurídicos que ordenan el Derecho internacional, a saber, “prohibición de uso de la fuerza, integridad territorial, soberanía, independencia, derechos humanos y cooperación”. Pero es incapaz de denunciar y reaccionar cuando todos ellos son violados.

Cualquier estudio objetivo de los conflictos internacionales en los últimos 30 años situará a la OTAN en el centro de la belicosidad mundial. Esa otra evidencia de la que en Occidente no queremos hablar. Carney, cuando habla de crear un “nuevo orden”, no se atreve a proponer el desmantelamiento de la OTAN. Al contrario, se reafirma en su adhesión a la misma. Cuando Europa y Canadá entiendan que la OTAN no necesariamente les ha protegido nunca, es posible que sí se inicie un cambio de era basado en las mismas normas de Derecho internacional que ya tenemos, pero más justo y equilibrado. Eso sí sería histórico. 

La propuesta de Canadá: más Derecho internacional

El “nuevo orden” que propone Carney es un mayor respeto al mismo sistema jurídico. Insiste, varias veces en su discurso, en apoyar un modelo basado en los principios y procedimientos que ya existen. No enmienda el Derecho internacional, sino que lo abraza. Una forma suave de reconocer que, hasta ahora, no lo hacían del todo. Una gran noticia.

Canadá se suma a lo que ya hacía el Sur Global, con Brasil, Sudáfrica, México, Colombia y, en menor medida, India, a la cabeza. Con más fuerza aún, los Estados pequeños y empobrecidos, los que necesitan el Derecho internacional para existir. 

Este EE. UU. de Trump ha reculado cada vez que el propio Canadá, México, Brasil o China han respondido a las amenazas en su contra, y su valentía les honra, con represalias, previstas en las normas internacionales. Trump solo sale victorioso de los encontronazos con la UE y el Reino Unido porque practican la técnica, estúpida ante un matón, de la distensión. Y Carney, sin duda un firme defensor de las represalias pacíficas, ha comprobado que funcionan

El primer ministro canadiense acusa a las “potencias” de desmontar el viejo orden mundial. Lo dice en genérico, pero sabe que esa estrategia es la estadounidense, no la del resto. Ni tan siquiera la de Rusia, potencia media también, que no puede liderar ningún cambio de calado. China no está jugando a eso y Carney lo sabe (y por eso pacta con ella). China defiende un orden basado en reglas comunes y previsibles, porque su forma de ampliar su influencia no es agresiva. 

¿Qué propone entonces Canadá? Propone, en lo jurídico, más cooperación, más diplomacia, más tratados internacionales, mejores organizaciones internacionales y más multilateralismo. Propone “inversiones colectivas”, “normas compartidas”, “diferentes coaliciones para diferentes cuestiones basadas en valores e intereses comunes” y “crear instituciones y acuerdos que funcionen tal y como se describe”. Es decir, construir más normas de Derecho internacional, partiendo de las existentes, que sean más efectivas, menos injustas.

En definitiva, Carney no viene a proponer un cambio jurídico internacional. Su discurso suena nuevo porque es un líder occidental. Es nuestro eurocentrismo el que nos ha impedido ver lo que ocurría. Canadá y la UE están sorprendidas ante la arrogancia y la violencia de EE. UU. El resto del mundo, no.

Carney no se atreve a romper del todo con EE. UU., pero sí hace una cosa crucial: anuncia públicamente el fin de la hegemonía estadounidense, también en el bloque occidental. Le niega el bilateralismo que Trump anhela, y exhorta al resto a seguir esa vía.  

Plantea un multilateralismo económica y militarmente neoliberal, favorable a las grandes empresas. En lo geopolítico, una suerte de “no alineamiento” frente a las potencias, siguiendo las propuestas del candidato de izquierda a la presidencia francesa, Jean Luc Melenchon. Tal vez las llamadas del Sur Global sobre un futuro con normas y valores respetados lleguen tanto a los liberales canadienses y los “rojos” europeos. Sería un inicio.

La entrada Canadá (re)descubre el Derecho internacional se publicó primero en lamarea.com.

23 Jan 17:04

How Google SREs Use Gemini CLI to Solve Real-World Outages

by Riccardo Carlesso

One of our favorite mottos in Google Site Reliability Engineering (SRE) is: "Eliminate Toil."

You hear it in the microkitchens in Zurich and the hallways in Mountain View. This motto refers to the SRE mission of replacing repetitive, manual work with engineered systems. But as a senior SRE once explained, this doesn't just mean writing a script to solve a problem once. It means building the automation that triggers that script at the exact right moment—often the hardest part.

AI has already revolutionized how we write code, but what about how we operate it? Can AI safely solve operational problems? Can it assist operators during a high-pressure outage without taking away control?

In this article, we’ll delve into real scenarios that Google SREs are solving today using Gemini 3 (our latest foundation model) and Gemini CLI—the go-to tool for bringing agentic capabilities to the terminal.

The Scenario: Fighting "Bad Customer Minutes"

Meet Ramón. Ramón is a Core SRE, meaning he works in the engineering group that develops the foundational infrastructure for all of Google's products: safety, security, account management, and data backends for multiple services.

When infrastructure at this layer has a hiccup, it’s visible across a massive range of products immediately. Speed is vital, and we measure it in Bad Customer Minutes. Every minute the service is degraded burns through our Error Budget.

To combat this, we obsess over MTTM (Mean Time to Mitigation). Unlike Mean Time to Repair (MTTR), which focuses on the full fix, MTTM is about speed: how fast can we stop the pain? In this space, SREs typically have a 5-minute Service Level Objective (SLO) just to acknowledge a page, and extreme pressure to mitigate shortly after.

Our incident usually follows four distinct stages:

  1. Paging: The SRE gets alerted.

  2. Mitigation: We "stop the bleeding" to reduce Bad Customer Minutes, often before we even know why it broke.

  3. Root Cause: Once users are happy, we investigate the underlying bug and fix it for good.

  4. Postmortem: We document the incident and add extensive action items on engineering teams, that are prioritised to ensure it never happens again.

Let's walk through a real (simulated) outage to see how Gemini CLI accelerates every step of this journey to keep MTTM low.

Step 1: Paging and Initial Investigation

Context: It's 11:00 AM. Ramón’s pager goes off for incident s_e1vnco7W2.

When a page comes in, the clock starts ticking. Our first priority isn't to fix the code—it's to mitigate the impact on users. Thanks to the extensive work on Generic Mitigations by Google SREs, we have a defined, closed, set of standard classes of mitigations (e.g., drain traffic, rollback, restart, add capacity).

This is a perfect task for an LLM: classify the symptoms and select a mitigation playbook. A mitigation playbook is an instruction created dynamically for an agent to be able to execute a production mutation safely. These playbooks can include the command to run, but also instructions to verify that the change is effectively addressing the problem, or to rollback the change.

Ramón opens his terminal and uses Gemini CLI. Gemini immediately calls the fetch_playbook function from ProdAgent (our internal agentic framework). It chains together several tools to build context:

  • get_incident_details: Fetches the alert data from our Incident Response Management system (description, metadata, prior instances, etc).

  • causal_analysis: Finds causal relations between different time series behaviour and generic mitigation labels.

  • timeseries_correlation: Finds pairs of time series that are correlated, which may help the agent find root causes and mitigation

  • log_analysis: Uses log patterns and volumetric analysis to determine anomalies on the stream of logs from the service.

image1 - playbooks

Based on the symptoms, Gemini recommends the borg_task_restart playbook (analogous to a Kubernetes pod restart) as the immediate mitigation. It knows exactly which variables to fill based on the alert context.

Gemini proposes the following action:

image2 - run playbook script

Ramón reviews the plan; it looks solid. He types:

"SGTM, execute the restart."

Keeping the human in the loop is important at the moment, to validate that mitigations that are going to be actuated make sense and are safe to apply to the system. In the future this will change, as we build confidence in the agents and their capabilities and new agentic safety systems.

Step 2: The Mitigation (Stopping the Bleeding)

Safety Check: Copilot, Not Autopilot

Before we execute, we need to address safety. We cannot simply let an autonomous agent operate autonomously on production infrastructure: a command that is safe under some conditions, or system state, may not be safe in other situations (for example: a binary rollback may generally be safe, but not when a service is receiving a configuration push).

This is where the CLI approach shines. It implements a multi-layer safety strategy to ensure the agent acts as a responsible copilot, not an autopilot.

  1. Deterministic Tools: The agent doesn't write random bash scripts; it selects from strictly typed tools (via Model Context Protocol) like borg_task_restart.

  2. Risk Assessment: Every tool definition includes metadata about its potential impact (e.g., safe, reversible, destructive). The system automatically flags high-risk actions for stricter review.

  3. Policy Enforcement: Even if the agent tries to execute a valid command, a policy layer checks if it's allowed in the current context (e.g., "No global restarts during peak traffic" or "Requires 2-person approval").

  4. Human-in-the-Loop: Finally, the CLI forces a confirmation step. The agent proposes the mutation, but Ramón authorizes it. This allows us to move at AI speed while maintaining human accountability.

  5. Audit Trails: Because every action is proxied through the CLI, we automatically log exactly what the AI proposed and what the human approved, satisfying compliance requirements.

The Execution

Moving from theory to practice is where things often get messy. In this instance, the restart fails.

In a manual world, this is where MTTM increases significantly. The operator has to context switch, open new dashboards, manually grep logs, and lose precious minutes while Bad Customer Minutes accumulate.

Instead, Gemini CLI catches the error and stays in the flow. It immediately analyzes the failure and notices a pattern: Our job is the only one in the cell failing; others are healthy.

image3b - find identifiers - CROPPED

This insight is crucial. It suggests the issue isn't the cluster, but our specific binary or configuration. Because Gemini surfaced in seconds rather than minutes, we avoid chasing red herrings. The "stop the bleeding" phase is paused, and we move to investigation with minimal time lost.

Step 3: Root Cause and Long-Term Fix

Now that we know a simple restart won't work, we need to find the bug. Since the infrastructure is healthy, the defect must be in the application logic. Ramón points Gemini to the source code. Since Google uses a massive monorepo, being able to pass a specific folder as context is powerful.

"Check the changes in /path/to/service/..."

image_4_sre_blog
image_5_sre_blog

Gemini starts fetching files, analyzing recent changes, and cross-referencing them with the production logs it pulled earlier. In under two minutes, it finds the culprit: a logic error in a recent configuration push.

Ramón asks:

"Can you make a CL fixing that issue?"

(Note: A CL, or Changelist, is the Google equivalent of a GitHub Pull Request).

Gemini generates the patch, creating a CL that reverts the bad configuration and applies a safeguard.

image_6_sre_blog

Gemini provides the instructions:

  1. Review and approve the CL.

  2. Submit the CL.

  3. Wait for the automated rollout.

The code is fixed, the rollout begins, and the service recovers.

Step 4: The Postmortem

The fire is out, but the work isn't done. SRE culture is built on the Postmortem: a blameless document that analyzes what went wrong so we can learn from it.

Writing postmortems can be tedious—gathering timestamps, linking logs, and recalling specific actions. Gemini CLI automates this with a Custom Command

postmortem Screenshot from 2026-01-09 11-03-31

Enter Riccardo: “Ricc” has worked with Google Cloud SREs for years, declared a few public outages and contributed to many Post Mortems; as a Developer Advocate, he also preaches about the Art of the Post Mortem , Art of SLOs, and Incident Management to Operators. He authored a Custom Command within ProdAgent which helps create Post Mortems, build timelines and Action Items.

Ramón runs his postmortem command. The tool:

  1. Scrapes the conversation history, metrics, and logs from the incident.

  2. Populates a CSV timeline of all relevant events.

  3. Generates a Markdown document based on our standard SRE Postmortem template.

  4. Suggests Action Items (AIs) to prevent reoccurrence.

image_7_sre_blog
image8 - pomo bigger writefile yellow CROPPED alta

Finally, Gemini uses the Model Context Protocol (MCP) to interact with our issue tracker:

  • Create Bugs: It files the Action Items as real bugs in the issue tracker.

  • Assign Owners: It assigns them to the relevant engineers.

  • Export Doc: It pushes the final Postmortem to Google Docs.

image_9_sre_blog

Conclusion

We just walked through a full incident lifecycle—from a chaotic 3 AM page to a finalized Postmortem—driven entirely from the terminal.

By using Gemini CLI, we connected the reasoning capabilities of Gemini 3 with real-world operational data. We didn't just ask a chatbot for advice; we used an agent to execute tools, analyze live logs, generate a code patch, and roll it out to production. This direct integration is what allows us to aggressively reduce MTTM and minimize Bad Customer Minutes.

While this story used some Google-internal tools, the pattern is universal. You can build this workflow today:

  • Gemini CLI is open for everyone.

  • MCP Servers allow you to connect Gemini to your own tools (Grafana, Prometheus, PagerDuty, Kubernetes, ..).

  • Custom Commands let you automate your specific team workflows, just like our Postmortem generator.

The Virtuous Cycle

Perhaps the most exciting part is what happens next. That Postmortem we just generated? It becomes training data. By feeding past Postmortems back into Gemini, we create a virtuous loop of self-improvement: the output of today’s investigation becomes the input for tomorrow’s solution.

Check out geminicli.com to find extensions for your stack and start eliminating toil.

23 Jan 17:03

Announcing availability of AWS Outposts racks in Rwanda

by aws@amazon.com

AWS Outposts racks can now be shipped and installed at your data center and on-premises locations in Rwanda.

AWS Outposts racks extend AWS infrastructure, AWS services, APIs, and tools to virtually any on-premises data center or colocation space for a truly consistent hybrid experience. Outposts racks allow customers to run workloads that need low latency access to on-premises systems locally while connecting back to a home Region for application management. Customers can also use Outposts racks to manage and process data that needs to remain on-premises to meet data residency requirements.

To learn more about Outposts racks, read the product overview and user guide. For the most updated list of countries and territories and the AWS Regions where Outposts racks are supported, check out the Outposts rack FAQs page.

23 Jan 14:33

How to Build a Singleton in Python (and Why You Probably Shouldn't)

by Bala Priya C

The singleton pattern ensures that a class has exactly one instance throughout your application. You've probably seen it in configuration managers, database connections, or logging systems. While singletons seem useful, they often create more problems than they solve.

In this tutorial, I'll show you how to implement singletons in Python, explain when they might be appropriate, and discuss better alternatives for most use cases.

You can find the code on GitHub.

Prerequisites

Before we start, make sure you have:

  • Python 3.10 or higher installed

  • Understanding of Python classes and decorators

  • Familiarity with object-oriented programming concepts

No external libraries needed as we'll use only Python's standard library.

Table of Contents

  1. What is a Singleton?

  2. The Classic Singleton Pattern

  3. The Decorator Pattern

  4. The Metaclass Approach

  5. Thread-Safe Singleton

  6. Why You Probably Shouldn't Use Singletons

  7. Better Alternatives to the Singleton Pattern

  8. When Singletons Are Acceptable

What Is a Singleton?

A singleton is a design pattern that restricts a class to a single instance. No matter how many times you try to create an object from that class, you always get the same instance back.

The classic use case is a configuration object. You want all parts of your application to share the same configuration, not create separate copies. Instead of passing the config object everywhere, the singleton pattern lets you access it globally.

Here's the problem: global state is problematic. When any part of your code can modify shared state, debugging becomes difficult. You lose the ability to reason about code in isolation. Tests become harder because they share state between runs.

Despite these issues, there are a few genuine use cases. Let's explore how to build singletons properly, then discuss when you actually need them.

The Classic Singleton Pattern

The traditional approach uses a class variable to store the single instance. When you try to create a new instance, the class checks if one already exists.

class DatabaseConnection:
    """
    Classic Singleton pattern using __new__
    """
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            print("Creating new database connection")
            cls._instance = super().__new__(cls)
            cls._instance._initialized = False
        return cls._instance

    def __init__(self):
        # Only initialize once
        if not self._initialized:
            print("Initializing database connection")
            self.connection_string = "postgresql://localhost/mydb"
            self.pool_size = 10
            self._initialized = True

    def query(self, sql):
        return f"Executing: {sql}"

Let’s now test the singleton behavior:

db1 = DatabaseConnection()
print(f"db1 connection: {db1.connection_string}")

print("\nCreating second instance:")
db2 = DatabaseConnection()
print(f"db2 connection: {db2.connection_string}")

print(f"\nAre they the same object? {db1 is db2}")

Output:

Creating new database connection
Initializing database connection
db1 connection: postgresql://localhost/mydb

Creating second instance:
Are they the same object? True

The __new__ method controls object creation in Python. By overriding it, we intercept instance creation and return our stored instance if it exists. The __init__ method still runs each time, so we add an _initialized flag to prevent re-initialization.

This pattern works, but it's verbose and easy to mess up. The _initialized flag feels like a hack. Let's look at cleaner approaches.

The Decorator Pattern

A more Pythonic approach uses a decorator to handle the singleton logic. This keeps the class clean and moves the singleton behavior to a reusable decorator.

def singleton(cls):
    """
    Decorator that converts a class into a singleton
    """
    instances = {}

    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return get_instance

@singleton
class AppConfig:
    """
    Application configuration as a singleton
    """
    def __init__(self):
        print("Loading configuration...")
        self.debug_mode = True
        self.api_key = "secret-key-12345"
        self.max_connections = 100
        self.timeout = 30

    def update_setting(self, key, value):
        setattr(self, key, value)
        print(f"Updated {key} = {value}")

As with the earlier approach, let’s test the decorator approach:

# First access
config1 = AppConfig()
print(f"Debug mode: {config1.debug_mode}")

# Second access - no re-initialization
print("\nAccessing config again:")
config2 = AppConfig()
config2.update_setting("timeout", 60)

print(f"\nconfig1 timeout: {config1.timeout}")
print(f"Same instance? {config1 is config2}")

Output:

Loading configuration...
Debug mode: True

Accessing config again:
Updated timeout = 60

config1 timeout: 60
Same instance? True

The decorator pattern is cleaner. The @singleton decorator wraps the class and maintains instances in a closure. This keeps singleton logic separate from the class implementation. The class itself remains simple and testable.

Notice how modifying config2 affects config1 as they're the same object. This shared state can be useful but also dangerous. Any code that gets the config can modify it, potentially breaking other parts of your application.

The Metaclass Approach

For more control, you can use a metaclass. Metaclasses control class creation itself, making them a natural fit for singletons.

class SingletonMeta(type):
    """
    Metaclass that creates singleton instances
    """
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            instance = super().__call__(*args, **kwargs)
            cls._instances[cls] = instance
        return cls._instances[cls]

class Logger(metaclass=SingletonMeta):
    """
    Simple logging singleton using metaclass
    """
    def __init__(self):
        self.logs = []

    def log(self, message):
        self.logs.append(message)
        print(f"[LOG] {message}")

    def get_logs(self):
        return self.logs

Let’s test the above metaclass approach to building a singleton:

# Use the logger from different parts of code
logger1 = Logger()
logger1.log("Application started")
logger1.log("User logged in")

# Another part of code gets the same logger
logger2 = Logger()
logger2.log("Processing request")

print(f"\nTotal logs in logger1: {len(logger1.get_logs())}")
print(f"Total logs in logger2: {len(logger2.get_logs())}")
print(f"Same logger? {logger1 is logger2}")

Output:

[LOG] Application started
[LOG] User logged in
[LOG] Processing request

Total logs in logger1: 3
Total logs in logger2: 3
Same logger? True

The metaclass approach is elegant if you're comfortable with metaclasses. The __call__ method intercepts class instantiation, allowing us to return the existing instance. This happens at a deeper level than __new__, making it more robust.

However, metaclasses add complexity. Most Python developers don't work with them regularly, making code harder to understand. Use this approach only if you need the additional control metaclasses provide.

Thread-Safe Singleton

The previous implementations aren't thread-safe. In multi-threaded applications, two threads might create instances simultaneously. Let's fix that.

import threading

class ThreadSafeSingleton:
    """
    Thread-safe singleton using a lock
    """
    _instance = None
    _lock = threading.Lock()

    def __new__(cls):
        if cls._instance is None:
            with cls._lock:
                # Double-check pattern
                if cls._instance is None:
                    print(f"Thread {threading.current_thread().name}: Creating instance")
                    cls._instance = super().__new__(cls)
                    cls._instance._initialized = False
        return cls._instance

    def __init__(self):
        if not self._initialized:
            with self._lock:
                if not self._initialized:
                    print(f"Thread {threading.current_thread().name}: Initializing")
                    self.data = {}
                    self._initialized = True

Now let’s test the above singleton with multiple threads and verify that it’s a singleton with only one instance:

# Test with multiple threads
def create_singleton(thread_id):
    instance = ThreadSafeSingleton()
    instance.data[thread_id] = f"Data from thread {thread_id}"

threads = []
for i in range(5):
    t = threading.Thread(target=create_singleton, args=(i,), name=f"Thread-{i}")
    threads.append(t)
    t.start()

for t in threads:
    t.join()

# Verify it's a singleton
final = ThreadSafeSingleton()
print(f"\nShared data across all threads: {final.data}")

Output:

Thread Thread-0: Creating instance
Thread Thread-0: Initializing

Shared data across all threads: 
{0: 'Data from thread 0', 
1: 'Data from thread 1', 
2: 'Data from thread 2', 
3: 'Data from thread 3', 
4: 'Data from thread 4'}

The lock ensures that only one thread creates the instance. The double-check pattern avoids acquiring the lock on every access. We only lock when the instance might be None. This is more efficient than locking every time.

Note on Python 3.13+: Python 3.13 introduced a build option for a free-threaded mode, and this has become more mainstream in Python 3.14. With true parallelism, thread safety becomes even more essential. The global interpreter lock (GIL) previously masked some race conditions by preventing true parallel execution. In free-threaded Python, explicit locking like this becomes essential for correctness, not just good practice. If you're writing code for Python 3.13+ with free-threading enabled, always use proper synchronization primitives like locks for shared mutable state.

Why You Probably Shouldn't Use Singletons

Now that you know how to build singletons, let me explain why you often shouldn't.

Singletons are global state in disguise. Global state makes code harder to understand, test, and maintain. When any code can access and modify a singleton, you lose the ability to reason about your code locally. Changes in one module can break another through shared state.

Singletons make testing difficult. Tests should be independent, but Singletons carry state between tests. You need to reset the singleton before each test, which is error-prone. Worse, you can't easily mock a singleton for testing.

Singletons violate the Single Responsibility Principle. The class handles both its core logic and the singleton mechanism. This mixing of concerns makes code harder to maintain.

Python has better alternatives. Module-level objects are natural singletons. Dependency injection provides better control. Context managers handle resource lifetime cleanly.

Better Alternatives to the Singleton Pattern

Instead of singletons, consider these patterns.

Module-level Instances

Module-level instances are Python's natural singleton. Import a module, and you get the same instance every time. Here’s how you can do it:

# config.py
class Config:
    def __init__(self):
        self.debug = True
        self.api_key = "secret-key"

    def update(self, key, value):
        setattr(self, key, value)

# Create a single instance at module level
config = Config()

This is simpler and more Pythonic. The module system ensures you get the same instance. No special patterns needed. You can use it like so:

# main.py
from config import config

config.update("debug", False)
print(f"Debug mode: {config.debug}")

Let’s now take a closer look at how and why this works. Python's module system is itself a singleton mechanism: when you import a module, Python executes it once and caches the result in sys.modules. Every subsequent import returns the cached module object, not a new one.

When config.py runs for the first time, it creates the Config instance and assigns it to the module-level variable config. This happens only once, during the initial import. Any other file that imports config from this module gets a reference to that same object, not a new instance. So from config import config in multiple files will always give you the exact same Config instance, achieving singleton behavior without any special patterns, metaclasses, or decorators.

Dependency Injection

Dependency injection gives you control without global state. It solves the singleton problem by making dependencies explicit parameters instead of hidden global state. Here’s an example:

class DatabaseConnection:
    def __init__(self, connection_string):
        self.connection_string = connection_string

    def query(self, sql):
        return f"Executing {sql}"

class UserRepository:
    def __init__(self, db):
        self.db = db

    def get_user(self, user_id):
        return self.db.query(f"SELECT * FROM users WHERE id = {user_id}")

Instead of UserRepository creating or accessing a global database singleton internally, it receives the database connection through its constructor (__init__). This means you control exactly which database instance gets used. In production you pass a real DatabaseConnection, but in tests you can pass a mock object that doesn't actually connect to a database.

The key here is that UserRepository doesn't know or care whether it's getting a singleton, a mock, or a fresh instance each time. It just knows it received something that has a query method.

# Create dependencies explicitly
db = DatabaseConnection("postgresql://localhost/mydb")
user_repo = UserRepository(db)

result = user_repo.get_user(123)

This makes the code's dependencies visible in the function signature, eliminates hidden global state, makes testing trivial (just pass different objects), and gives you complete control over object lifecycles without needing any singleton patterns at all.

When Singletons Are Acceptable

Despite the drawbacks, some cases justify the use of singletons. Here are some of them:

Hardware interfaces that represent unique physical resources. You might have one camera, one printer, or one GPIO interface. A singleton models this accurately.

Caching layers where you want a single shared cache across your application. Though even here, dependency injection might be cleaner.

Thread pools or connection pools where you want to limit and share expensive resources. The pool itself might be a singleton, though the resources it manages aren't.

Even in these cases, ask yourself: could I use dependency injection instead? Could I make this a module-level instance? The answer is often yes.

Conclusion

I hope you found this tutorial helpful. You've learned several ways to implement singletons in Python: the classic pattern, decorators, metaclasses, and thread-safe variants. Each approach has trade-offs in complexity, readability, and thread safety.

More importantly, you've learned why singletons often aren't the best solution. Global state, testing difficulties, and violation of design principles make Singletons problematic. Module-level instances and dependency injection usually provide better alternatives.

When you reach for a Singleton, pause and ask: do I really need shared global state? Often the answer is no. But when you do need it, now you know how to implement it properly.

Use singletons sparingly, if at all.

23 Jan 07:30

Israel paga anuncios en el Reino Unido atacando a Médicos Sin Fronteras (EN)

by Tkachenko

El esfuerzo de Benjamin Netanyahu por expulsar a las organizaciones benéficas médicas de Gaza, respaldado por una agresiva campaña de propaganda israelí en Gran Bretaña.

etiquetas: sionismo, genocidio, gaza, palestina, reino unido, médicos sin fronter

» noticia original (www.declassifieduk.org)

23 Jan 07:29

Un ave declarada extinta hace medio siglo reaparece con ocho polluelos, sobrevive sólo en cautiverio, moviliza a los zoológicos internacionales, desafía el colapso y reaviva planes

by Leclercia_adecarboxylata

Un ave declarada extinta hace medio siglo reaparece con ocho polluelos, sobrevive sólo en cautiverio, moviliza a los zoológicos internacionales, desafía el colapso provocado por las especies invasoras, reaviva los planes de reintroducción y demuestra que la extinción no siempre es definitiva para la conservación. Se trata de una variante de la paloma torcaz: la paloma de Socorro.

etiquetas: ave, extinta, polluelos

» noticia original (es.clickpetroleoegas.com.br)

23 Jan 07:29

Groenlandia: en Dinamarca crece el uso de apps para boicotear productos de EE. UU

by Grahml

Las aplicaciones "NonUSA" y "Made O'Meter" han escalado con rapidez en las listas de descargas de tiendas digitales como la App Store y Google Play en Dinamarca, con un crecimiento promedio de descargas de 867% en la última semana en comparación con la anterior, según datos de la firma de inteligencia de mercado Appfigures y reportes de TechCrunch. En la App Store danesa, NonUSA llegó incluso al primer puesto entre las apps más descargadas, habiendo estado en el puesto 441 apenas días atrás.

etiquetas: groenlandia, boicot, productos, eeuu, usa, nonusa

» noticia original (www.lanacion.com.ar)

23 Jan 07:29

La lección canadiense para los europeos sobre cómo lidiar con EE.UU. boicoteando sus productos

by mmlv

Bajo el lema "codos arriba", derivado del hockey, que aboga por una postura defensiva y de resistencia, los consumidores canadienses han llevado a cabo un boicot masivo de bienes y servicios estadounidenses. Uno de los ejemplos más visibles es el boicot a las bebidas espirituosas estadounidenses. Como resultado, de enero a septiembre de 2025, las exportaciones estadounidenses de bourbon y whisky a Canadá cayeron un 60%.

etiquetas: canada, trump, eeuu, boicot, consumidores

» noticia original (es.euronews.com)

23 Jan 07:29

Federico Montalbán López: "La pobreza somete a la gente a una tensión continuada que acaba por agotarla"

by Grymyrk

Por una parte, seguimos pensando que la pobreza es culpa de quien la sufre y por eso quien está en pobreza procura que no se note. Al mismo tiempo, tenemos la intuición de que la pobreza tiene causas colectivas, no tiene que ver con los comportamientos o méritos individuales o familiares y sí con la organización económica y social que nos hemos dado. Ver la pobreza es también ver esto último y enfrentarse a la responsabilidad de acometer cambios profundos en nuestro modelo de sociedad. Y nadie parece querer asumir esa responsabilidad.

etiquetas: pobreza, gente, murcia, desigualdad, economía

» noticia original (www.eldiario.es)

23 Jan 07:29

España descubre cómo saber cuándo va a estallar un volcán con dos días de antelación

by Lord_Cromwell

Anticipar una erupción volcánica en plena ciudad ya no es ciencia ficción. Un equipo de científicos españoles ha desarrollado una metodología pionera capaz de avisar con hasta 48 horas de antelación de una erupción de un volcán, un avance que puede cambiar por completo la gestión de emergencias naturales en zonas habitadas.

El método ha sido desarrollado por expertos del Instituto Geológico y Minero de España (IGME-CSIC), el Instituto Geográfico Nacional (IGN) y la Universidad de Valencia, y sus resultados se han publicado en la revista...

etiquetas: españa, volcán, erupciones, antelación, descubrimiento

» noticia original (www.laopiniondezamora.es)

23 Jan 07:29

EEUU autoriza a China a comprar petróleo venezolano, pero bajo sus reglas y precios

by teneram

Estados Unidos confirmó que permitirá a China seguir comprando petróleo venezolano, pero ya no bajo las condiciones que durante años beneficiaron al chavismo. La administración de Donald Trump ha dejado claro que Pekín podrá adquirir crudo venezolano únicamente a “precios justos de mercado”, y no a los valores rebajados con los que el régimen de Maduro saldaba deudas políticas y financieras con China.

etiquetas: eeuu, china, venezuela, petróleo

» noticia original (hch.tv)

23 Jan 07:28

Un implante en la retina devuelve visión central a 38 personas con ceguera avanzada

by xaviazo

La atrofia geográfica es una forma avanzada de la degeneración macular asociada a la edad (DMAE), una enfermedad ocular que afecta principalmente a personas mayores. Esta condición daña de manera progresiva la parte central de la retina, llamada mácula, que es esencial para ver detalles, leer, reconocer rostros y realizar actividades cotidianas.

etiquetas: atrofia geográfica, degeneración macular, retina, ceguera, implante

» noticia original (comunidad-biologica.com)

23 Jan 07:28

En serio, ¿qué podemos hacer con el fascista que ahora anda suelto por Estados Unidos?

by JanSmite

Amigos: Agentes del ICE han secuestrado a un niño de 5 años para utilizarlo como «cebo» y arrestar a sus padres. El niño y su padre se encuentran ahora en un centro de detención en Texas, aunque nadie sabe su paradero exacto. Estaban en Estados Unidos de forma legal. Esta es solo la última atrocidad cruel de la que he oído hablar. Todo esto se está haciendo en nuestro nombre —los Estados Unidos de América— con nuestra autoridad, el dinero de nuestros impuestos y, al parecer, nuestro consentimiento.

etiquetas: trump, fascismo, autoritarismo

» noticia original (robertreich.substack.com)

23 Jan 07:28

El peloteo de 'La Razón' destacando el 'look' de Ayuso... en el minuto de silencio por las víctimas de Adamuz: "Ascopena nivel premium"

by Delay

Hasta ahora habíamos visto alabanzas a Ayuso por llevar un abrigo de plumas o un vestido negro. La novedad ahora ha sido destacar su look... en el minuto de silencio por las víctimas de la tragedia de Adamuz.

etiquetas: la razón, ayuso, look, minuto de silencio, adamuz

» noticia original (www.publico.es)

23 Jan 07:25

En boca de bobos (hora veintipico)

by comunerodecastilla

De vuelta a nuestras payasadas, Héctor de Miguel se ha vuelto a poner la peluca calva para una de sus mejores imitaciones... -relacionada: www.meneame.net/story/nacho-abad-pierde-papeles-invitado-pedia-respeto

etiquetas: carroñeros, nacho abad, cuatro

» noticia original (www.youtube.com)

23 Jan 07:25

Italia, España y Portugal solo recibirán fondos de ayuda para la COVID-19 tras llevar a cabo reformas (Eng)

by Verdaderofalso

En negociaciones sobre fondos de recuperación post-COVID-19, Rutte defendió que Italia, España y Portugal solo recibieran ayuda financiera si se aplicaban reformas económicas acordadas. Esto fue percibido por muchos como exigir demasiadas condiciones a los países del sur antes de darles soporte.

etiquetas: rutte, españa, italia, portugal, coronavirus

» noticia original (www.brusselstimes.com)

23 Jan 07:25

ICE secuestra a un niño porque no tiene a mano una prueba de ciudadanía [Eng]

by Mangione

El niño sólo llevaba a mano un snack para comer...

etiquetas: ice, nazis, gestapo, camisas pardas, usa, fascismo

» noticia original (www.reddit.com)

23 Jan 07:25

Una bodega de vinos, convertida en espacio de exaltación neonazi, anuncia un acto de Núcleo Nacional en Almería

by GustavoEnfurecido

Raúl Sánchez, el heredero del negocio Bodega Nieto de Matías situado en Almería, ha transformado este establecimiento en un espacio de exaltación neonazi, algo que puede comprobarse a través de las publicaciones difundidas desde la cuenta pública del propio local en redes sociales, abierta y accesible para cualquier usuario.

etiquetas: falange, franquismo, fascismo, noviembre nacional

» noticia original (www.diario-red.com)

23 Jan 07:24

Los internautas denuncian el pacto entre el Ministerio y LaLiga: "una calla y la otra ejecuta impunemente"

by Lord_Cromwell

La Secretaría de Estado de Telecomunicaciones e Infraestructuras Digitales (SETID) es el encargado de vigilar la neutralidad de la red en España y garantizar entre otros aspectos, que los operadores no aplican bloqueos injustificados a su servicio de acceso a internet. Este es el papel que le atribuye la Ley General de Telecomunicaciones. Aunque la norma contempla los bloqueos por razones legales, también recuerda que las medidas de gestión del tráfico deben ser "transparentes, no discriminatorias y proporcionadas", algo que definitivamente...

etiquetas: internautas, pacto, ministerio, laliga, internet, bloqueos

» noticia original (bandaancha.eu)

23 Jan 07:24

Sánchez anuncia que España no participará en la Junta de Paz de Gaza propuesta por Trump

by Rivethead

El presidente del Gobierno, Pedro Sánchez, ha intervenido desde el Consejo Europeo en Bruselas tras la reunión a la que este jueves han acudido los líderes europeos en el marco de las tensiones con Estados Unidos por Groenlandia. Un encuentro al que también han asistido el presidente francés, Emmanuel Macron, el canciller alemán, Friedrich Merz, o la presidenta de la Comisión Europea, Ursula von der Leyen, y en el que los líderes han abordado su relación con Washington, que esta semana ha rebajado su amenaza arancelaria con un principio...

etiquetas: palestina, donald trump, israel, pedro sánchez

» noticia original (cadenaser.com)

23 Jan 07:24

Moreno Bonilla responde con solemnidad a Ayuso sobre Adamuz: "Hace tres horas hemos recuperado dos cadáveres. No quiero entrar en polémicas"

by Delay

"Estamos en luto oficial. Hace escasamente tres horas que hemos recuperado dos cadáveres. No quiero entrar en polémicas. Tiempo habrá para que se investigue y se sepa lo sucedido", ha contestado el presidente de la Junta de Andalucía.

etiquetas: moreno bonilla, ayuso, funeral, cadáveres, adamuz

» noticia original (www.lasexta.com)

23 Jan 07:24

Trump cede el liderazgo de la economía mundial y China gana

by Murciegalo

"Europa y China son, en cierto modo, aliados naturales en una época en la que Estados Unidos ha optado por el brío nacionalista. Ambos siguen oficialmente comprometidos con el concepto de un comercio internacional basado en normas, aunque se acuse con frecuencia a China de incumplirlas. Los dos afirman la realidad científica del cambio climático, al tiempo que movilizan inversiones y conocimientos para combatirlo."

etiquetas: trump, china, liderazgo

» noticia original (www.nytimes.com)

23 Jan 07:22

¿Para qué fue María Jesús Montero a Adamuz con los Reyes?

by Bardock

43 muertos

etiquetas: ministra, foto, vergüenza, ajena

» noticia original (finofilipino.org)

23 Jan 07:21

Yolanda Díaz evita respaldar a los maquinistas que irán a la huelga y se retrata

by BLUESS

La ministra de Trabajo, desde Adamuz, se limita a mostrar el «respeto absoluto al derecho a huelga» de cualquier trabajador

etiquetas: yolanda díaz, huelga maquinistas, ferrocarriles, gobierno de españa

» noticia original (www.eldebate.com)

23 Jan 07:21

Los controles internos del Ejecutivo de Ayuso ven incumplimientos y errores en la gestión de siete hospitales público-privados

by Cayetan卐

EL PAÍS accede a un informe de la Intervención regional que desvela obras tramitadas “en contra de las previsiones legales” o fallos en la imputación presupuestaria del canon y los gastos ajenos al contrato

etiquetas: gestión económica, hospitales público-privados, incumplimientos, madrid

» noticia original (elpais.com)