liveBook · Manning

Global variable

As explained in The Quick Python Book, Fourth Edition

A global variable is a name bound at module or program level that can be accessed and modified by functions that explicitly declare it global.

A global variable is bound at module or program level. Code outside functions can access it, and a function can access or modify it after declaring the name with global. section 9.4 section 10.9

Keep these scope rules in view:

  • Function parameters and names assigned inside a function are local by default. section 9.4
  • Declare a name global before using it in the function when an assignment should change the module-level binding. section 9.4
  • Without global, assigning to a same-named local variable does not change the outside variable. section 9.4
  • Use nonlocal for a variable in the nearest enclosing function scope; global targets the module-level variable. section 9.4

Changing a module-level value

a = "one"\nb = "two"\n\ndef fun():\n global a\n a = 1\n b = 2\n\nfun()\n# a is now 1; b is still "two"

A global dictionary as a cache

sole_cache = {}\n\ndef sole(m, n, t):\n if (m, n, t) in sole_cache:\n return sole_cache[(m, n, t)]\n # perform the expensive calculation\n sole_cache[(m, n, t)] = result\n return result\n\nThe shared dictionary stores results by argument tuple, avoiding repeated calculations for identical calls. section 7.6

Avoid confusing names during refactoring

cleaned_line = clean_line(line)\nwrite_words_to_file(cleaned_line, output_file)\n\nAssigning the return value to clean_line instead would replace the function name with a string, causing the next call to fail with a TypeError. section 9.9.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains local-versus-global assignment, contrasts nonlocal scope, and demonstrates results without descending into interpreter internals.
Examples
Demonstrates modifying a shared scalar, preserving a local shadow, updating nested scopes, and memoizing results in a dictionary.
What it assumes
Assumes familiarity with function definitions, arguments, and parameters while establishing local and global scope distinctions.
What you can do after
Apply it via Python to share module-level state, update it deliberately, and diagnose name-shadowing or refactoring errors.
How it connects
Connects global variables with functions, local variables, nonlocal variables, modules, namespaces, and dictionaries.

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 The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.