This is an old copy of the Python FAQ. The information here may be outdated.

How do you set a global variable in a function?

Q. I’m trying to change a module variable, but it doesn’t work. Can it be done?

A. Did you do something like this?

x = 1 # make a global module variable

def f():
      print x # try to print the global
      ...
      for j in range(100):
           if q > 3:
              x=4

Any variable assigned in a function is local to that function, unless it is specifically declared global. Since a value is bound to x as the last statement of the function body, the compiler assumes that x is local. Consequently the “print x” statement attempts to print an uninitialized local variable and will trigger a UnboundLocalError (or in earlier Python versions, a NameError).

The solution is to insert an explicit global declaration at the start of the function:

def f():
      global x
      print x # try to print the global
      ...
      for j in range(100):
           if q > 3:
              x=4

In this case, all references to x are interpreted as references to the x from the module namespace.

Note that the global declarations must be placed at the beginning of the function, and that it affects all uses of the variable inside the function.

If you want to create program-wide global variables, see this article:

how-do-i-share-global-variables-across-modules

CATEGORY: programming

 

A Django site. rendered by a django application. hosted by webfaction.