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
share|improve this question

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:

from redis import StrictRedis
import os

_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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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