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











