Settings

Theme

Shades of Singleton design pattern – Python

medium.com

3 points by yashness · 3 comments

Reader

1 thread
justinl33

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

  • odie5533

    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_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

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection