12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Here, x, y, and z are all globals inside the function all_global. y and z are globalbecause they aren’t assigned in the function; x is global because it was listed in aglobal statement to map it to the module’s scope explicitly. Without the global here,x would be considered local by virtue of the assignment.Notice that y and z are not declared global; <strong>Python</strong>’s LEGB lookup rule finds them inthe module automatically. Also, notice that x might not exist in the enclosing modulebefore the function runs; if not, the assignment in the function creates x in themodule.Minimize Global VariablesBy default, names assigned in functions are locals, so if you want to change namesoutside functions, you have to write extra code (global statements). This is bydesign—as is common in <strong>Python</strong>, you have to say more to do the “wrong” thing.Although there are times when globals are useful, variables assigned in a def are localby default because that is normally the best policy. Changing globals can lead to wellknownsoftware engineering problems: because the variables’ values are dependent onthe order of calls to arbitrarily distant functions, programs can become difficult todebug.Consider this module file, for example:X = 99def func1( ):global XX = 88def func2( ):global XX = 77Now, imagine that it is your job to modify or reuse this module file. What will thevalue of X be here? Really, that question has no meaning unless qualified with a pointof reference in time—the value of X is timing-dependent, as it depends on whichfunction was called last (something we can’t tell from this file alone).The net effect is that to understand this code, you have to trace the flow of controlthrough the entire program. And, if you need to reuse or modify the code, you haveto keep the entire program in your head all at once. In this case, you can’t really useone of these functions without bringing along the other. They are dependent (that is,coupled) on the global variable. This is the problem with globals—they generallymake code more difficult to understand and use than code consisting of selfcontainedfunctions that rely on locals.On the other hand, short of using object-oriented programming and classes, globalvariables are probably the most straightforward way to retain state information(information that a function needs to remember for use the next time it is called) inThe global Statement | 317

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!