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 again, the best prescription is generally not to do this—the best way to communicateacross file boundaries is to call functions, passing in arguments, and gettingback return values. In this specific case, we would probably be better off coding anaccessor function to manage the change:# first.pyX = 99def setX(new):global XX = new# second.pyimport firstfirst.setX(88)This requires more code, but it makes a huge difference in terms of readability andmaintainability—when a person reading the first module by itself sees a function, hewill know that it is a point of interface, and will expect the change to the variable X.Although we cannot prevent cross-file changes from happening, common sense dictatesthat they should be minimized unless widely accepted across the program.Other Ways to Access GlobalsInterestingly, because global-scope variables morph into the attributes of a loadedmodule object, we can emulate the global statement by importing the enclosingmodule and assigning to its attributes, as in the following example module file. Codein this file imports the enclosing module by name, and then by indexing sys.modules,the loaded modules table (more on this table in Chapter 21):# thismod.pyvar = 99def local( ):var = 0def glob1( ):global varvar += 1def glob2( ):var = 0import thismodthismod.var += 1def glob3( ):var = 0import sysglob = sys.modules['thismod']glob.var += 1# Global variable == module attribute# Change local var# Declare global (normal)# Change global var# Change local var# Import myself# Change global var# Change local var# Import system table# Get module object (or use _ _name_ _)# Change global varThe global Statement | 319

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

Saved successfully!

Ooh no, something went wrong!