Tom Ritchford
Jun 7, 2024

--

Senior engineer here. Singletons aren't great, but sometimes they're necessary.

But this solution makes the problem worse!

For one thing, it isn't thread-safe, so you could create a second instance of the class if there were a race condition - which could easily happen if you started two threads which both tried to get a DB connection.

But why would you do this at the class level? It makes that class almost impossible to unit test, amongst many other issues.

If you need a global singleton, create a global variable, and that's the end of it.

If the variable can't be constructed as your program starts up and you need that variable to be lazily created on first use, consider using functools.cache.

--

--

Responses (1)