|
|
|
|
|
by justinl33
536 days ago
|
|
Python'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.