\$\begingroup\$
\$\endgroup\$
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
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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
lang-py