liveBook · Manning

Global variable

As explained in Python Workout: 50 ten-minute exercises

A global variable is a variable defined outside a function and accessible through the module's global scope.

A global variable is defined outside a function and belongs to the global scope. Python displays it in the global frame, alongside globally defined functions and classes. section 1.4

Name lookup follows LEGB: local, enclosing function, global, then built-ins. Inside a function, Python searches these scopes in order and stops when it finds the name; outside a function, it searches globals and built-ins. section 6.5

Global and local names can coexist, but assignment inside a function normally creates a local name.

  • With x = 100 outside foo and x = 200 inside foo, foo prints its local x while the outer x remains 100. section 6.5
  • Add global x inside foo to make the assignment target the outer x; calling foo then changes the global value from 100 to 200. section 6.5
  • A global name can shadow a built-in: assigning sum = 0 makes sum([10, 20, 30]) fail because Python finds the integer first. section 6.5

Changing a global explicitly

x = 100 def foo(): global x x = 200 print(x) print(x) foo() print(x) The first print shows 100, the function changes the global name, and the final print shows 200. Without global x, foo would bind a local x instead. section 6.5

x = 100

def foo():
   global x
   x = 200
   print(x)

print(x)
foo()
print(x)

Step through the global statement example to compare the outer name before and after the function call. section 6.5

Imported names also enter the current global scope. from os import sep defines sep globally, while import os keeps the name under the module object as os.sep. Import * broadly creates global names and is discouraged when unnecessary. section 8.0

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Works through LEGB, local shadowing, explicit global assignment, built-in collisions, and imported names.
Examples
Uses Python Tutor frames, inner and outer x values, a global counter-style update, sum shadowing, and os imports.
What it assumes
Assumes functions and assignments, then develops local, enclosing, global, and built-in scope relationships.
What you can do after
Diagnose/debug with Python Tutor by tracing global and local frames, detecting shadowed names, and predicting function effects.
How it connects
Connects global variables to local variables, enclosing functions, built-ins, modules, imports, and namespaces.

Also explained in

Compare how 12 books explain global variable →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.