Why are global variables evil? [closed]

I'm trying to find out why the use of global is considered to be bad practice in python (and in programming in general). Can somebody explain? Links with more info would also be appreciated.


Solution 1:

This has nothing to do with Python; global variables are bad in any programming language.

However, global constants are not conceptually the same as global variables; global constants are perfectly harmless. In Python the distinction between the two is purely by convention: CONSTANTS_ARE_CAPITALIZED and globals_are_not.

The reason global variables are bad is that they enable functions to have hidden (non-obvious, surprising, hard to detect, hard to diagnose) side effects, leading to an increase in complexity, potentially leading to Spaghetti code.

However, sane use of global state is acceptable (as is local state and mutability) even in functional programming, either for algorithm optimization, reduced complexity, caching and memoization, or the practicality of porting structures originating in a predominantly imperative codebase.

All in all, your question can be answered in many ways, so your best bet is to just google "why are global variables bad". Some examples:

  • Global Variables Are Bad - Wiki Wiki Web
  • Why is Global State so Evil? - Software Engineering Stack Exchange
  • Are global variables bad?

If you want to go deeper and find out why side effects are all about, and many other enlightening things, you should learn Functional Programming:

  • Side effect (computer science) - Wikipedia
  • Why are side-effects considered evil in functional programming? - Software Engineering Stack Exchange
  • Functional programming - Wikipedia

Solution 2:

Yes, in theory, globals (and "state" in general) are evil. In practice, if you look into your python's packages directory you'll find that most modules there start with a bunch of global declarations. Obviously, people have no problem with them.

Specifically to python, globals' visibility is limited to a module, therefore there are no "true" globals that affect the whole program - that makes them a way less harmful. Another point: there are no const, so when you need a constant you have to use a global.

In my practice, if I happen to modify a global in a function, I always declare it with global, even if there technically no need for that, as in:

cache = {}

def foo(args):
    global cache

    cache[args] = ...

This makes globals' manipulations easier to track down.