1

I am trying to assign a value from a dictionary to a variable but the variable remains unchanged. The value is another dictionary.

The code I used to generate the dictionaries can be found here: http://pastebin.com/Q2Hc8Ktp

I wrote it myself and tested it without this problem.

Here is the code snipit of me trying to copy the dictionary from the dictionary.

_classes = {}

def populateClasses():
    print "Classes Exist"
    cp = Preferences(''.join([resource_path,"resources.ini"]))
    print cp
    _classes = cp.getPreferences()['Classes']

populateClasses()
print _classes

When I print out cp it shows the correct data but when I try to print _classes it only shows {}

Note: printing _classes from within the function works as expected but not from outside the function. _classes is defined in the global scope

-Edit-

Here is also some sample data:

[Classes]
Wizard = Arcana, Bluff
Warrior = Endurance, Intimidate
Ranger = Nature, Perception
Bard = Heal, History
Lost Sorcerer
  • 905
  • 2
  • 13
  • 26
  • use `global _classes = {} http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them – scroll_lock May 12 '13 at 06:27

2 Answers2

4

If you want to change the value of the global variable _classes, you need to use global:

def populateClasses():
    global _classes   # <<<<<< THIS
    print "Classes Exist"
    cp = Preferences(''.join([resource_path,"resources.ini"]))
    print cp
    _classes = cp.getPreferences()['Classes']

Without this, your method creates a separate local variable also called _classes. This variable goes out of scope as soon as your method returns.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

Rather than global, you might use _classes.update(cp.getPreferences()['Classes']).

The rule for globals is that you need the global keyword if you write to it, but don't need it if you're just accessing the variable (even if that access is mutating the state). That's why my suggestion above doesn't need a global statement, and the original code does. Possibly that's also what happened when you "assigned lists to two variables" and didn't need global.

Paul Hankin
  • 54,811
  • 11
  • 92
  • 118