[Tutor] Use of global (was: help on scope)

Doug Stanfield DOUGS@oceanic.com
Mon, 23 Jul 2001 08:29:05 -1000


[Charlie Clark responded:]
> >The easiest relief for the brain pain is to not cause it in 
> the first place.
> >;-)  Avoid scope problems by explicitly moving all variables 
> in and out of
> >functions.  For yours it would change it thus:
> >
> >def func(something,count):
> >     print count
> >     count += 1
> >     return count
> 
> that's a good tip even it looks a little clumsy.
> 
> >If you have lots of variables that need to move through the function,
> >organise them with classes.
> 
> I'm writing a little program that makes anagrams. Something I 
> failed to do 
> miserably in basic when I first dabbled in programming 20 
> years ago. I'm 
> using count to help me check whether the algorithm is working 
> properly. As I 
> use a recursive function I need to initialise my counter 
> outside the function 
> but increment with each new word. Passing the counter as an 
> argument removes 
> problems of scope but feels wrong. I agree, however, that it 
> is better than 
> using global. Am I missing something?

This is probably one of those "feelings" left over from your 20 year old
Basic experiences.  Its sometimes called a paradigm shift.  Explicitly
passing of variables into functions makes it easier to understand what
you're doing.  As I said before, everytime I've used 'global' I've regretted
it later when I started to do more with my functions than I originally
thought.  It may not be apparent to you with this program in its current
form.  It may be that starting to develop a habit now will pay off later.  I
know that now it just 'feels' right to me to _not_ use 'global if there is
another way.

-Doug-