LarsVegas LarsVegas - 18 days ago 6
Python Question

Why are global variables evil?

I was trying to find a good source that explains why the use of

global
is considered to be bad practice in python (and in programming in general). Can somebody point me to one or explain here?

Answer

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 fine to use. It's just that in Python there is no syntactic difference.

The reason they are bad is that they allow functions to have hidden (as in "non-obvious" and "undeclared") and thus hard to understand side effects. Also, this can lead to Spaghetti code.

Also, limited/controlled/conscious use of globals is acceptable, just as local state (i.e. mutable variables) are acceptable in Functional Programming, either for performance reasons or simplicity, or for caching/memoization.

But of course, that short question of yours really has many long answers, so your best bet is to just google "why are global variables bad". Some examples:

If you want to go deeper and find out why side effects are (usually, or at least often) bad (and many other enlightening things), you should learn Functional Programming:

Comments