Python function global variables?

Akshat Shekhar picture Akshat Shekhar · May 14, 2012 · Viewed 609.7k times · Source

I know I should avoid using global variables in the first place due to confusion like this, but if I were to use them, is the following a valid way to go about using them? (I am trying to call the global copy of a variable created in a separate function.)

x = "somevalue"

def func_A ():
   global x
   # Do things to x
   return x

def func_B():
   x = func_A()
   # Do things
   return x

func_A()
func_B()

Does the x that the second function uses have the same value of the global copy of x that func_a uses and modifies? When calling the functions after definition, does order matter?

Answer

Levon picture Levon · May 14, 2012

If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.

E.g.

global someVar
someVar = 55

This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.

The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.