2
\$\begingroup\$

Here's my class for providing a singleton instance of a Redis connection. What do you think?

from redis import StrictRedis
import os

class RedisConnection(object):
    REDIS_URL = os.environ['REDIS_URL']

    def __init__(self):
        self._redis = StrictRedis.from_url(self.REDIS_URL)

    def redis(self):   
        return self._redis

    the_instance = None
    @classmethod
    def singleton(cls):
        if cls.the_instance == None:
            print "assigning!"
            cls.the_instance = cls().redis()
        return cls.the_instance
\$\endgroup\$
4
\$\begingroup\$

The Singleton pattern is a way to work around the absence of global variables in Java. But Python has global variables, and it's usually possible to write shorter and simpler initialization code if you use them, for example:

import os

from redis import StrictRedis

_connection = None

def connection():
    """Return the Redis connection to the URL given by the environment
    variable REDIS_URL, creating it if necessary.

    """
    global _connection
    if _connection is None:
        _connection = StrictRedis.from_url(os.environ['REDIS_URL'])
    return _connection

Alternatively, you could memoize the function, for example using functools.lru_cache:

from functools import lru_cache
import os

from redis import StrictRedis

@lru_cache(maxsize=1)
def connection():
    """Return the Redis connection to the URL given by the environment
    variable REDIS_URL, creating it if necessary.

    """
    return StrictRedis.from_url(os.environ['REDIS_URL'])
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.