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.

<strong>Python</strong>—local variables disappear when the function returns, but globals do not.Other techniques, such as default mutable arguments and enclosing function scopes,can achieve this, too, but they are more complex than pushing values out to the globalscope for retention.Some programs designate a single module to collect globals; as long as this isexpected, it is not as harmful. Also, programs that use multithreading to do parallelprocessing in <strong>Python</strong> essentially depend on global variables—they become sharedmemory between functions running in parallel threads, and so act as a communicationdevice (threading is beyond this book’s scope; see the follow-up texts mentionedin the Preface for more details).For now, though, especially if you are relatively new to programming, avoid thetemptation to use globals whenever you can (try to communicate with passed-inarguments and return values instead). Six months from now, both you and yourcoworkers will be happy you did.Minimize Cross-File ChangesHere’s another scope-related issue: although we can change variables in another filedirectly, we usually shouldn’t. Consider these two module files:# first.pyX = 99# second.pyimport firstfirst.X = 88The first defines a variable X, which the second changes by assignment. Notice thatwe must import the first module into the second file to get to its variable—as we’velearned, each module is a self-contained namespace (package of variables), and wemust import one module to see inside it from another. Really, in terms of this chapter’stopic, the global scope of a module file becomes the attribute namespace of themodule object once it is imported—importers automatically have access to all of thefile’s global variables, so a file’s global scope essentially morphs into an object’sattribute namespace when it is imported.After importing the first module, the second module assigns its variable a new value.The problem with the assignment, however, is that it is too implicit: whoever’scharged with maintaining or reusing the first module probably has no clue that somearbitrarily far-removed module on the import chain can change X out from underhim. In fact, the second module may be in a completely different directory, and sodifficult to find. Again, this sets up too strong a coupling between the two files—because they are both dependent on the value of the variable X, it’s difficult to understandor reuse one file without the other.318 | Chapter 16: Scopes and Arguments

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

Saved successfully!

Ooh no, something went wrong!