Skip to content

Globals are Bad or Not

russ_hensel edited this page May 12, 2026 · 2 revisions

Generally

We are taught that globals are bad. Too many are, but they sure can be handy. For example think about logging. You surely do not want to pass a logging object to every piece of code that might want to log

It may be instructive to realize that modules are all global singletons and we often take advantage of this in our code. If you want a value to be available everywhere then just assign it to a module instance variable

so_for golbal.py:

ANSWER = 42

then anywhere in any other module in your application

import global.py
print( global.ANSWER ) # prints  42

this also works for Class objects in a module where you use class variables. You can access value and even change them.

These are automatically singletons. Other methods trickily create objects that can only be created once, second attempts to create them return the first instance.

I have messed with a bunch of these techniques and have not be consistent in which method I use. This is not good but is the way it is.

More Specifically

  • Some modules are imported and a method is run that creates an object for the module and assigns it to a module variable.

global_object.py

MY_OBJECT = None
class MyObject.....

if MY_OBJECT is None
   MY_OBJECT = MyObject()

in use

import global_object
something   = global_object.MY_OBJECT.some_value_or_method

What you may find in actual use.

  • AppGlobal in app_global.py ......
  • global_vars.py is just a module with "constants" values may be monkey patched in. Once set they are expected to be treated as constants

Global variables are typically set up when the application begins and never changed. As much as pratical they are set by the main module of the application.

Some thing that are typically made global.

  • parametes
  • the gui and its methods
  • the central controler for the application
  • access to system tools like a text editor
  • logging tools
  • db access

Clone this wiki locally