Python - Using global variables in a function

Python - Using global variables in a function

global, python, variables

A few of the most common Python questions revolve around global variables. How can I create or use a global variable in a function? If you create a global variable in one function, how can it be used as a global variable in another function? 

Check out our example of using global variables in a function below.


testvar = 0

def set_testvar_to_one():
    global testvar    # Needed to modify global copy of testvar
    testvar = 1

def print_testvar():
    print(testvar)     # No need for global declaration to read value of testvar

print_testvar()       # Prints 1

What are the rules for local and global variables in Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as ‘global’.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

Back to The Programmer Blog