[Tutor] global variables

Alan Gauld alan.gauld at btinternet.com
Thu Aug 22 16:04:42 CEST 2013


On 22/08/13 13:36, Matthew Ngaha wrote:
> I'm always told to avoid using them.

Global variables  in themselves are not the problem.
It's how they tend to get used that causes problems.
Read-only global values - aka constants (so not
really variables!) - are not an issue.

Globals that are only changed via a set of
dedicated functions are not topo much of a
problem - although they should probably be
bundled as a class (or module) if you have
such features available.

> i can't avoid using them. Like where i want to
 > keep track of a state variable in many
> different functions

Usually that should be in a class. A class represents
a set of operations using common data. Therefore shared
state would naturally fit in a class along with the
operations which depend on/modify that state.

You may then have a single global variable which
is the instance of that class.

> also not wanting any of the functions to return it to the
> caller.

Thats more problematic and usually a sign of a bad design.
Even if using global variables you should modify them
explicitly via return values of functions rather than
as hidden side-effects inside other functions.

mystate = changestate(mystate, some, other, args)

> My question is how many global variables did your last decent sized
> program have?

I usually have not more than a half dozen plus one per
thousand lines of code. So in a 10,000 line program I'd
expect to have less than 16 in total (actually I'd hope
less than 10!). And many of those would be instances
of classes. I would not expect to have more than one
or two fundamental typed globals (ints, strings, bools etc),
if any.

> Also please share any insight you have about them. I do
> try to avoid them, but is this always possible?

It is possible but only by playing silly games with
semantics such as:

class MyProgram
    global1 = 0
    global2 = True

    def __init__(self, lots, of, args,
       self.inst1 = .... # initialise program runtime vars
    def run(self)
       # my program code all goes here
       # and accesses the class level globals and instance
       # level runtime and state values

if __name__  = __main__":
     MyProgram(args....).run()

[Or alternatively you can hide them inside a database.]

Now technically there are no globals but in fact we are
just moving them inside the meaningless class and have
all the same potential issues with global side effects
etc.

In my experience there are usually a few globals required
for any meaningful program. It's not avoiding globals
completely that's important, it's being careful to use
them sensibly and with good adherence to the principles
of coupling and cohesion in the design.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list