31. globalization is a bad thing.

Suppose you are writing a long program together with a friend. Because you have learned good programming practices, you are always trying to use descriptive names for your variables. But then you start thinking: What if my friend uses the same name as I use for one of her variables? If I make a change to the value of my variable, will it change hers in an unwanted way?

Python has ways to help you avoid this kind of problem by the use of namespaces. This prevents variable that we want to use in a small part of a program to affect other parts. We will start learning about namespaces in this lesson.


Locally defined variables.

Here's a simple example to try:

>>> a = 1
>>> def my_function():
...     a = 3
...     print a
...    

>>> my_function()
3

>>> print a
1

Are you surprised that the value of a did not change? Here's what's happened.

You started by defining a variable names "a" with its value set to 1. Then, inside a function, you "apparently" changed the value of "a" to 3. Actually, what you did was to create a new variable "a" inside the function, and gave it a value of 3. The value of the other variable "a" was left unchanged.

Python automatically creates a namespace inside each function, where the names of variables defined take a unique value, independent of how other variables with the same name outside the function might be defined. A namespace is like a little notebook in which Python keeps track of all the variable names. It is as though Python create a unique notebook for each function, so that you don't have to worry if other variables with the same name exist elsewhere.

The variables used inside a function are no longer defined when the function ends; we say that they are out of scope.

>>> def simple_function():
...     local_variable = "I'm here!"
...     print local_variable
...    
>>> simple_function()
I'm here!

>>> print local_variable
Traceback (most recent call last):
  File "<input>", line 1, in ?
NameError: name 'local_variable' is not defined

This namespace trick is nice, but what if we want to change the value of a variable inside a function? For example, suppose we want to keep track of how many times we are calling a certain function. We can do that, using the Python keyword global.

>>> number_of_times = 0
>>> def two_year_old_child():
...     global number_of_times
...     number_of_times += 1
...     print "Why?     %s times" % number_of_times
...    
>>> two_year_old_child()
Why?          1 times # I know, it should be "1 time", without a final 's'

>>> two_year_old_child()
Why?          2 times

>>> two_year_old_child()
Why?          3 times

>>> print number_of_times
3

By using the keyword global, we tell Python not to create a new version of the variable locally inside the function, but rather use the variable with that name "outside", in the so-called "global" environment.

You should always try to find ways to avoid using global variables if you can, as they can introduce unwanted changes in other parts of the program. In programming, globalization is usually a bad thing.


Out of scope

Larry and Curly are walking merrily together. Suddenly, Moe sees his friends from a distance and starts running towards them. Just as Moe finally catches up with Larry and Curly, he goes out of scope and disappears from the screen. If you want for him to keep up with his friends, you need to remove three # symbols.

Larry = UsedRobot(colour='blue')
Curly = UsedRobot(1, 3, colour='green')

# Using two keywords you haven't seen yet!
for i in range(3):
    Larry.move()
    Curly.move()

def wait_for_me():
    #global Moe
    Moe = UsedRobot(1, 2, colour='yellow')
    # Using two same new keywords again!
    for i in range(3):
        Moe.move()
        Larry.move()
        Moe.move()
        Curly.move()

wait_for_me()
# first image below; Moe is there.
Larry.move()
# second image below; Moe is gone.
Curly.move()
#Moe.move()
Larry.move()
Curly.move()
#Moe.move()
Larry.turn_off()

Moe there

Moe gone


Try it!

Try this program on your own, in Reeborg's world, and then change it so that Moe can keep up with his friends!

previousObject-Oriented Programming: "dot" notation. - home - Many returns next