Skip to content
Python for Quantitative Finance / Functions and Decomposition

Global Variables and Modular Program Design

Every function this topic has built so far communicates with the rest of the program only through its parameters and its return value — the discipline this vault treats as the default. This closing note of the topic covers the one legitimate escape hatch from that discipline, the global keyword, using it to instrument the recursive fib from the previous note with a call counter. Having shown the mechanism, the note then makes the case — following Functions, Parameters, and Scoping's UnboundLocalError example — for why global mutable state should remain a rare exception, not a habit, and closes Stage 3 by naming the design principle (procedural decomposition, parameters and return values as the default channel of communication) that every later topic in this unit assumes.
Learning objectives. By the end of this note you should be able to:
  • use the global keyword correctly to declare that a name assigned inside a function refers to a module-level variable, not a new local one;
  • explain why, absent global, a name assigned anywhere in a function body is local to it — connecting back to the scoping rule from Functions, Parameters, and Scoping;
  • articulate the locality argument against indiscriminate global-variable use, and identify a legitimate use case where a global variable is the right tool;
  • restate, as a design summary, why parameters and return values are the preferred default channel for a function to communicate with its environment.

In this lesson

  1. The global keyword
  2. Why global mutable state is usually the wrong tool
  3. Closing Stage 3: the design principle

Before you start

The full lesson, with worked examples and exercise solutions, is for members.

Read the full lesson

New to SelfMadeQuant.com? See membership options or browse the Python for Quantitative Finance syllabus.