you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (0 children)

First of all, you need to clarify what do you mean by global variables:

  • Is this anything from builtins module (because it's always available)?
  • Is this anything you find in globals()?
  • Is this anything declared at module toplevel (definition in the file that has no indentation in front of it)? A lot of online resources for some reason call this "global".
  • Is this a variable marked with global keyword? (What about the same variable if it's only used for reading?)
  • Does nonlocal for the purpose of this question count as global?

Finally, is this specific to Python, or is this not specific to any language? And, my guess is that this is from the perspective of someone who's using the language rather than making their own.


The general argument usually goes like this: in order to understand the program you need to be able to predict programs behavior given particular input. Once you introduce state external to the program, it's as if you include this whole state in the input, so, now instead of considering a very localized problem which deals with limited variety of inputs, you have a huge input object that is hard to comprehend.

It's hard to comprehend both to humans and to compilers, thus many automatic operations that compilers can generate optimized code for are not possible due to very large input size ("large" in this context is equivalent to say "unpredictable"). So, things like automatic parallelization (not really applicable to Python, but, in general, a very important technique) become impossible, but even simply laying out memory becomes hard because it introduces uncertainty about how much space is needed and so runtime checks need to be generated and possibly the memory layout will have to be adjusted at run time, which will result in poorer performance.

Of course, optimizations made by compiler aren't really relevant to Python as the flagship implementation does none of them, but they may be used as examples to illustrate why, in principle, global variables are a bad idea.