Python Singleton Pattern Not Required

TIL: You don’t need to explicitly implement the Singleton pattern in Python. Python modules are loaded only once per interpreter session. This means you can define an object at the module level and simply import it wherever needed, the same instance will be reused automatically. Sometimes, the language itself already solves the problem for you. 🐍✨ #python #singleton #design

Don't use singleton... what the hell are you doing? And just because you don't HAVE to do something doesn't mean you shouldn't.

Like
Reply

This feels like a bit of a sketchy thing to rely on to me.

You can use functools lru_cache decorator for the same and is often the best alternative

Interesting, a very clean way to initialize shared resources like a database client across an entire application using simple code

See more comments

To view or add a comment, sign in

Explore content categories