Why are global variables evil?

global-variables, python, side-effects

Solution

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

Problem

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.

Original source

Related problems