3 ms·
Shades of Singleton design pattern – Python
- justinl33 2y agoPython's module loading mechanism is thread-safe by default, and module-level variables are effectively singletons. This would suffice: _connection = None def get_connection(): global _connection if _connection is None: _connection = create_connection() return _connection
- odie5533 2y agoThis is what I always use. It looks like a code smell, but it's extremely easy to read and even someone that just learned Python yesterday can understand what's happening. If I need a lot of state, I'll make a class to go with it. But usually it's just your example. One variation I use is if you don't want the connection module knowing how to get the connection settings, you can make another method like init_connection(settings) and then get_connection() just throws a RuntimeError if it's not initialized yet. _connection = None def init_connection(settings): global _connection _connection = create_connection(settings) def get_connection(): if not _connection: raise RuntimeError("Connection must be initialized before trying to use it. Make sure you call init_connection() in your startup.") return _connection
- justinl33 2y agonice, thanks for sharing!