Better Programming

Advice for programmers.

Follow publication

Member-only story

Alternatives to Using Globals in Python

When to use them and when to let go of them

Keno Leon
Better Programming
Published in
6 min readDec 13, 2019

--

Photo by Fernando @dearferdo on Unsplash

I am by no means an expert in Python, but after a few years of developing with it more or less exclusively (JavaScript, I still love you!), I’m starting to feel comfortable enough to write about it.

This short article is about global variables and how to use them (or not). But most importantly, it’s about alternatives to them — something that usually gets omitted.

What Is a Global?

A global variable is simply a variable that’s accessible from anywhere in your program. Consider these examples:

INIT = Falsedef run():
global INIT
print('Will Run')
if INIT:
print( 'Already initiated' )
if not INIT:
init()
def init():
global INIT
INIT = True
print('Will Init')
run()
run()
OUTPUT:Will Run
Will Init
Will Run
Already initiated

Both the run() and init() functions have access to the INIT variable via the global keyword. This allows for the following logic: run init() once, set the INIT variable to True, and then check if it has already ran (via the INIT variable). If so, don’t run it again.

--

--

Responses (4)

Write a response