[Tutor] Global Variables

Steven D'Aprano steve at pearwood.info
Sat Jun 22 12:08:25 CEST 2013


On 22/06/13 18:09, Jack Little wrote:
> Is there a way to keep a global throughout multiple def statements?

Oh, a further thought! Perhaps you mean something like this?


x = 42  # Global value.

def function_one():
     global x  # Define it once.
     code using global x goes here...

def function_two():
     # x is already declared global, so no need to do it again
     code using global x goes here...


# Run the code.
function_one()
function_two()


If that's what you mean, the answer is, thank goodness, no, there is no way to do this!

Relying on global variables is, as a general rule, a good way to end up with unmaintainable, buggy code that cannot easily be tested and is frustrating to debug. Sixty years of experience in programming has lead to the conclusion that global variables are best avoided.

To be precise, it is not so much the *global variable* part that is harmful, but the reliance on side-effects in the code: calling a function invisibly gets input from a global, and outputs to a global. We can get better, safer, easier to understand code by using explicit input arguments and a return result:


def function_one(arg):
     code using argument "arg" goes here...
     return result of calculation

def function_two(arg):
     code using "arg" goes here...
     return result of calculation


# Run the code.
x = 42
x = function_one(x)
y = function_two(x)


In this case, we can see that the value of x is passed to function_one as input. There's no need to guess that it magically uses some global variable. We can also see that the result of that calculation is stored back into x. Then in the next line, the new value of x is passed to function_two as input, and the result is stored in a different variable, y.


Although there is a very slight increase in the amount of typing, with practice and experience this leads to more maintainable, more easily debugged code.


-- 
Steven


More information about the Tutor mailing list