Claiming a topic: why global variables are a bad idea

Nov 6, 2012 • Luis Figueira

I’d like to try to explain why global variables are (usually) a bad idea.

Most times people start writing a Python program as a script, which they believe will be concise and self explanatory.

Most times these scripts evolve into something much larger, and sometimes can even become a module.

An easy way to avoid worrying about function arguments and return values is to use global variables. These belong to the global scope of a program, and therefore all functions share them — meaning that all functions have access and can modify their values.

In a small program this is easy to keep track of, but in larger ones this can become a true problem.

In order to make my case against globals, I’ll assume that the user is familiar with: scopes, functions and variables.

Global Vars Concept Map<figcaption class="wp-caption-text">Global Vars — initial version of concept map</figcaption></figure> Above you can find my first tentative version of a concept map for global variables. What I’m somehow finding hard to explain — without using too many boxes — is where the variables live in the different scopes of a program.

Programming examples to follow — maybe these will help me improving the map!

Example

# number of instruments in the orchestra
global nInst

nInst = 0;

def initialise_number_of_instruments():
  nInst = 10;

def add_two_instruments_to_orchestra():
  global nInst;

  nInst = nInst + 2;

initialise_number_of_instruments();
add_two_instruments_to_orchestra();

print nInst;

I created a global variable (nInst) to be shared between all my functions. In this very small example I’ve got 2 functions that change the number — one that initialises it with 10 instruments, another that adds 2 more. The final result is not exactly what I was expecting it to be — 2 instead of 12. Only then I noticed that I forgot to declare nInst as global in one of my functions.