In summary, my problem is how do you easily make a connection resource a global variable? To be specific, I’d like to open a Redis queue connection and would like to use that in multiple functions without the hassle of passing it as a parameter, i.e.’
#===============================================================================
# Global variables
#===============================================================================
REDIS_QUEUE <- how to initialize
Then, in my main function, have
# Open redis queue connection to server
REDIS_QUEUE = redis.StrictRedis(host=SERVER_IP, port=6379, db=0)
And then use REDIS_QUEUE in multiple functions, e.g.
def sendStatusMsgToServer(statusMsg):
print "\nSending status message to server:"
print simplejson.dumps(statusMsg)
REDIS_QUEUE.rpush(TLA_DATA_CHANNEL, simplejson.dumps(statusMsg))
I thought REDIS_QUEUE = none would work but it gives me
AttributeError: 'NoneType' object has no attribute 'rpush'
I’m new to Python, what’s the best way to solve this?
If you want to set the value of a global variable from inside a function, you need to use the
globalstatement. So in your main function:Note that there’s no need to “initialize” the variable outside
mainbefore doing this, although you may want to just to document that the variable exists.