Python Global Variables

Global variables live at the top level of a program and can be read from anywhere, but changing them inside a function needs the global keyword.

Global vs. local

A variable created outside of any function is a global variable, and it is visible throughout the whole module, including inside functions. A variable created inside a function is a local variable and exists only while that function runs. This separation lets functions use helper values without accidentally clobbering names elsewhere.

Reading a global from inside a function

greeting = "Hello"

def welcome():
    print(greeting + ", world")

welcome()   # Hello, world

Reading a global inside a function is easy, but assigning to a name inside a function normally creates a new local variable that shadows the global. The global value stays untouched once the function returns.

Assignment creates a local by default

count = 10

def change():
    count = 99      # this is a new local variable
    print(count)    # 99

change()
print(count)        # 10, the global is unchanged

The global keyword

When you genuinely need a function to modify a global variable, declare it with the global keyword at the top of the function. This tells Python that assignments to that name should update the module-level variable rather than create a local one.

Modifying a global on purpose

count = 10

def change():
    global count
    count = 99

change()
print(count)        # 99
Note: Overusing global variables makes code hard to test and reason about, because any function might change them. Prefer passing values in as arguments and returning results whenever you can.
ScopeWhere it is definedWhere it can be used
GlobalAt the top level of the moduleAnywhere in the module, read-only inside functions unless declared global
LocalInside a functionOnly inside that function, for the duration of the call
  • Globals are readable from inside functions without any special keyword.
  • Plain assignment inside a function makes a local variable, not a change to the global.
  • Use the global keyword to rebind a module-level variable from within a function.
  • Keep globals to a minimum; explicit arguments and return values are usually clearer.