Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Shades of Singleton design pattern – Python (medium.com/learn-design-patterns)
3 points by yashness on Jan 6, 2025 | hide | past | favorite | 3 comments


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


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


nice, thanks for sharing!




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: