Using Global Variables and Constants


Through the magic of encapsulation, the functions you've seen are all totally sealed off and independent from each other and the main part of your program. The only way to get information into them is through their parameters, and the only way to get information out of them is from their return values. Well, that's not completely true. There is another way that you can share information among parts of your program: through global variables.

Understanding Namespaces

Namespaces (also called scopes) represent different areas of your program that are separate from each other. For example, each function you define has its own namespace. That's why the functions you've seen can't directly access each other's variables. A visual representation really helps to gel this idea, so take a look at Figure 6.7.


Figure 6.7: This simple program has three different namespaces— one for each function, plus one for the global namespace.

Figure 6.7 shows a program with three different namespaces. The first is defined by function func1(), the second is defined by function func2(), and the third is the global namespace (which all programs automatically have). In this program, you're in the global namespace when you're not inside any function. The shaded area in the figure represents the global namespace. Any variable that you create in the global namespace is called a global variable, while any variable you create inside a function is called a local variable (it's local to that function).

Since variable1 is defined inside func1(), it's a local variable that lives only in the namespace of func1(). variable1 can't be accessed from any other namespace. So, no command in func2() can get at it, and no command in the global space can access or modify it either.

A good way to remember how this works is to think of namespaces as houses and encapsulation as tinted windows, giving each house privacy. As a result, you can see anything inside a house if you're in it. But if you're outside a house, you can't see what's inside. This is the way it works with functions. When you're in a function, you have access to all of its variables. But when you're outside a function, like in the global namespace, you can't see any of the variables inside a function.

If two variables have the same name inside two separate functions, they're totally different variables with no connection to each other. For example, if I created a variable called variable2 inside function func1(), it would be different and completely separate from the variable named variable2 in function func2(). Because of encapsulation, it would be like they exist in different worlds and have no effect on each other.

Global variables, however, create a little wrinkle in the idea of encapsulation, as you'll see.

Introducing the Global Reach Program

The Global Reach program shows how you can read and even change global variables from inside functions. Figure 6.8 displays the program's results.

click to expand
Figure 6.8: You can read, shadow, or even change the value of a global variable from inside a function.

Here's the code for the program:

 # Global Reach # Demonstrates global variables # Michael Dawson - 2/21/03 def read_global():     print "From inside the local namespace of read_global(), value is:", value def shadow_global():     value = -10     print "From inside the local namespace of shadow_global(), value is:", value def change_global():     global value     value = -10     print "From inside the local namespace of change_global(), value is:", value # main # value is a global variable because we're in the global namespace here value = 10 print "In the global namespace, value has been set to:", value, "\n" read_global() print "Back in the global namespace, value is still:", value, "\n" shadow_global() print "Back in the global namespace, value is still:", value, "\n" change_global() print "Back in the global namespace, value has now changed to:", value raw_input("\n\nPress the enter key to exit.") 

Reading a Global Variable from Inside a Function

Although by now you're probably quite comfortable with the idea of encapsulation, I'm going to throw you a little curve ball: you can read the value of a global variable from within any namespace in your program. But fear not, this can still work with the concept of houses and tinted windows. Remember, tinted windows keep the houses (or functions) private. But tinted windows also let you see out. So, you can always see outside of a function to the global namespace and see the value of a global variable. That's what I did when I created the function read_global(). It prints the global variable value without a problem.

While you can always read the value of a global variable in any function, you can't change it directly (at least not without asking specifically for that kind of access). So, in read_global(), doing something like the following would generate a nasty error:

     value += 1 

Back to the houses and tinted glass idea, this means that you can see a global variable from within a function through the tinted window, but you can't touch it because it's outside. So, although you can read the value of a global variable from inside a function, you can't change its value without asking for special access to it.

Shadowing a Global Variable from Inside a Function

If you give a variable inside a function the same name as a global variable, you shadow the global variable. That is, you hide it with your new variable. It might look like you can change the value of a global variable by doing this, but you only change the local variable you've created. That's what I did in the function shadow_global(). When I assigned -10 to value with

     value = -10 

I didn't change the global version of value. Instead, I created a new, local version of value inside the function and that got -10. You can see that this is what happened, because when the function finishes, the main program prints out the global version of value with

 print "Back in the global namespace, value is still:", value, "\n" 

and it's still 10.

TRAP

It's not a good idea to shadow a global variable inside a function. It can lead to confusion. You might think you're using a global variable when you're really not. Be aware of any global variables in your program and make sure not to use the name anywhere else in your code.

Changing a Global Variable from Inside a Function

To gain complete access to a global variable, use the keyword global like I did in the function change_global():

     global value 

At this point, the function has complete access to value. So when I changed it with

     value = -10 

the global variable value got -10. When the program prints value again back in the main part of the code with

 print "Back in the global namespace, value has changed to:", value 

-10 is printed. The global variable was changed from inside the function.

Understanding When to Use Global Variables and Constants

Just because you can, doesn't mean you should. This is a good programming motto. Sometimes things are technically possible, but not good ideas. Using global variables is an example of this. In general, global variables make programs confusing because it can be hard to keep track of their changing values. You should limit your use of them as much as you can.

Global constants (global variables that you treat as constants), on the other hand, can make programs less confusing. For example, say you're writing a business application that calculates someone's taxes. Like a good programmer, you have written a variety of functions in your code, all of which use the somewhat cryptic value .27 as the tax rate. Instead, you could create a global constant called TAX_RATE and set it to .27. Then, in each function, you could replace the number .27 with TAX_RATE. This produces two benefits. It makes your code clearer and it makes changes (like a new tax rate) no sweat.




Python Programming for the Absolute Beginner
Python Programming for the Absolute Beginner, 3rd Edition
ISBN: 1435455002
EAN: 2147483647
Year: 2003
Pages: 194

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net