1

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?

3
  • What do you mean "the main program"? Where are you defining global variables if not in the main program? (That is, why don't you just do REDIS_QUEUE = redis.StrictRedis(...) right away.) Commented Jan 30, 2013 at 3:33
  • Place the instance in module. Then, in other files, import it. Commented Jan 30, 2013 at 3:34
  • Sorry, I meant "main function". Commented Jan 30, 2013 at 3:35

1 Answer 1

4

If you want to set the value of a global variable from inside a function, you need to use the global statement. So in your main function:

def main():
    global REDIS_QUEUE
    REDIS_QUEUE = redis.StrictRedis(host=SERVER_IP, port=6379, db=0)
    # whatever else

Note that there's no need to "initialize" the variable outside main before doing this, although you may want to just to document that the variable exists.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.