Search code examples
pythonpygameglobal-variablesglobaldeclare

Declaring Global Variables in Python Outside of Functions


Forgive me if this has been asked before, but I cannot figure it out as to why this doesn't work. I have Googled for hours, for the record. I keep getting a global variable error. I declare my globals as such:

###Sprites###
global_AB = []
global_AM = []
global_AD = []
global_BB = []
global_CO = []
global_DK = []
global_FB = []
global_O = []
global_R = []
global_SS = []
global_S = []
global_WU = []

But when I access it inside a function (after it's been set by this function)

#Loads all of the sprites and backgrounds, I recommend you close this if looking at the code.
def loadImages():
    for i in range(0, (len(spriteNames) - 1)):
        for z in range(0, numSprites[i]):
            if i == 0:
                AB.append(pygame.image.load(spriteNames[i] + str(z) + ".png_scaled.png"))
            elif i == 1:
                AM.append(pygame.image.load(spriteNames[i] + str(z) + ".png_scaled.png"))
            elif i == 2:
                AD.append(pygame.image.load(spriteNames[i] + str(z) + ".png_scaled.png"))
           ... 8 more of these

When accessed by the blit image I get an error saying it's not defined (I tried to blit AB[0] onto the surface),

If you know of an alternative way please let me know. I previously coded in JASS (which is why I have a funky way of declaring global variables), and I don't know how else to keep the lists able to be accessed in all functions.

Thanks so much! - Zach


Solution

  • In order to use a global, you need to actually explicitly set it in your method. Here is an example that should help you:

    glb = "I am global"
    
    def foo():
        global glb
        glb = "I changed you mr. global"
    
    foo()
    # Outputs:  I changed you mr. global
    print(glb)