[Tutor] visibility of variables

Alan G alan.gauld at freenet.co.uk
Mon Aug 1 23:00:20 CEST 2005

> I have problems with the visibility of variables in python. I am
> used to the idea of Javascript and other languages where one can 
> define
> global variables if they are defined outside a function. It seems 
> Python
> is not doing that, but how can I make it work?

Kent has answered the question of how to do it in Python but I would
point out that using global variables is, in general, considered
bad practice. It is best to minimise their use as muh as possible
and pass data into functions and return values from them.

There usually are a few globals in any program so don't worry
too much about them. BUt on the otherhand if most of your functions
are writing to global variables then your program design probably
needs rethinking!

> around this? I could add gemetenkleur in the argument list of the 
> funct1
> and funct2 functions, but in my case I don't want this (funct1 will 
> be a
> function to be used in scipy.fmin, and I have the idea that only the
> simplex can be as an argument).

Passing the values as arguments would IMHO be much better in your case
Consider your code, slightly rewritten (with shorter names! :-) to 
what I think you are trying to do:


def funct1(g):
    print 'g in func1: ',g
    print a

def funct2(k):
   print 'k in funct2 (should be same as g): ',k
   return 1

def Do(b,f):
   print 'g has to be from now b: ',g
   return g

G = Do(b,funct1)
print G

> Hope someone can help me. I have the idea this is essential to
> understand before continuing more in Python.

You might also look at the 'What's in a Name' topic in my tutor
for more on this (There is a slightly old German translation too).

Alan G
Author of the Learn to Program web tutor

More information about the Tutor mailing list