Steven D'Aprano <[EMAIL PROTECTED]> wrote: > >> >.... but you do keep having to use a longer reference to the value so > >> >what have you won? > >> > >> Clarity, simplicity, robustness > > > > Clarity - why is it clearer? > > Consider two function calls: > > > x = ham(arg, counter) > y = spam(arg) > > Both do exactly the same thing: ham() takes an explicit "counter" > argument, while spam() uses a global variable. Which one makes it clear > that it uses a counter, and which does not? > But you're not comparing what the OP posted. He was comparing a global with an object with a single variable inside it. Either would work with the y = spam(arg) example above.
I agree absolutely about the reason for not using globals but that applies similarly to objects. The OP was comparing a global integer variable with an object with a single integer variable in it. > > > Simplicity - no, you've added an extra layer. > > Consider trying to run ham() and spam() twice, independently: > > x1 = ham(arg, counter) > x2 = ham(arg, another_counter) > > y1 = spam(arg) > saved_counter = counter # save the global variable > counter = 0 # reset it to zero > y2 = spam(arg) > another_counter = counter > counter = saved_counter > > Which is simpler? Again it's not what the OP was doing. I again agree absolutely that in general globals are a 'bad thing' if you can avoid them but your example doesn't really affect the original OP question. > > > > > Robustness - how? > > If you avoid the use of globals, this code will work as expected: > > x = ham(arg, counter) > assert counter.n = 5 # or whatever value ham() sets it to... > function() > another_function() > yet_another_function() > > At the end of this block of function calls, you can be confident that > counter still has the same value. > > Now consider using globals: > > x = spam(arg) > assert counter = 5 # or whatever value spam() sets it to... > function() > another_function() > yet_another_function() > > What value will counter have? The only way to tell is to carefully read > through function(), another_function() and yet_another_function() and see > whether or not they modify the global counter. Maybe they do, maybe they > don't, who can tell? > You're just telling me all the problems one can have with globals which I know and agree with. But an object with a single variable in it has exactly the same issues. -- Chris Green -- http://mail.python.org/mailman/listinfo/python-list