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
asked Apr 27, 2016 at 17:38
\$\endgroup\$

1 Answer 1

6
\$\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'])
answered May 8, 2016 at 17:14
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.