Shades of Singleton design pattern – Python
1–4 of 4 posts
Re: Shades of Singleton design pattern – Python
#2_connection = None
def get_connection(): global _connection if _connection is None: _connection = create_connection() return _connection
Re: Shades of Singleton design pattern – Python
#3Python'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
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 _connectionRe: Shades of Singleton design pattern – Python
#4Python'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
This 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_connecti…