1

I have a problem where I am setting some global varaibles within a function. But when I go to access these global variables outside the function (in the main part of the script) those global varaibles were never set?

Why do the following global variables always equal 0 and not 1? How can I set the global variables within my function?

currentUserClientID             = 0
currentUserMaxLicences          = 0
currentUserActivatedLicences    = 0

def setGlobals():
    currentUserClientID             = 1
    currentUserMaxLicences          = 1
    currentUserActivatedLicences    = 1
    print "Set Globals"
    print currentUserClientID
    print currentUserMaxLicences
    print currentUserActivatedLicences

setGlobals()

print "Global Values"
print currentUserClientID
print currentUserMaxLicences
print currentUserActivatedLicences

Output:

Set Globals
1
1
1
Global Values
0
0
0
Mack
  • 179
  • 3
  • 13
  • possible duplicate of [Using global variables in a function other than the one that created them](http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them) – Martey Apr 04 '14 at 04:05

2 Answers2

3

You have to declare the variables as global. Put the global keyword before each variable declaration inside the function.

def setGlobals():
    global currentUserClientID
    global currentUserMaxLicences
    global currentUserActivatedLicences
    currentUserClientID = 1
    currentUserMaxLicenses = 1
    currentUserActivatedLicenses = 1
    print "Set Globals"
    print currentUserClientID
    print currentUserMaxLicences
    print currentUserActivatedLicences
gregkow
  • 560
  • 2
  • 11
2

Simply use the global keyword:

def setGlobals():
    global currentUserClientID, currentUserMaxLicences, currentUserActivatedLicences
    currentUserClientID             = 1
    currentUserMaxLicences          = 1
    currentUserActivatedLicences    = 1
    print "Set Globals"
    print currentUserClientID, currentUserMaxLicences, currentUserActivatedLicences
aIKid
  • 26,968
  • 4
  • 39
  • 65