12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

The second module, modb.py, defines its own global variable X, and imports andcalls the function in the first module:X = 11# My X: global to this file onlyimport modamoda.f( )print X, moda.X# Gain access to names in moda# Sets moda.X, not this file's XWhen run, moda.f changes the X in moda, not the X in modb. The global scope for moda.fis always the file enclosing it, regardless of which module it is ultimately called from:% python modb.py11 99In other words, import operations never give upward visibility to code in importedfiles—an imported file cannot see names in the importing file. More formally:• Functions can never see names in other functions, unless they are physicallyenclosing.• Module code can never see names in other modules, unless they are explicitlyimported.Such behavior is part of the lexical scoping notion—in <strong>Python</strong>, the scopes surroundinga piece of code are completely determined by the code’s physical position in yourfile. Scopes are never influenced by function calls or module imports. *Namespace NestingIn some sense, although imports do not nest namespaces upward, they do nestdownward. Using attribute qualification paths, it’s possible to descend into arbitrarilynested modules and access their attributes. For example, consider the nextthree files. mod3.py defines a single global name and attribute by assignment:X = 3mod2.py in turn defines is own X, then imports mod3 and uses qualification to accessthe imported module’s attribute:X = 2import mod3print X,print mod3.X# My global X# mod3's Xmod1.py also defines its own X, then imports mod2, and fetches attributes in both thefirst and second files:* Some languages act differently and provide for dynamic scoping, where scopes really may depend on runtimecalls. This tends to make code trickier, though, because the meaning of a variable can differ over time.408 | Chapter 19: Module Coding Basics

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

Saved successfully!

Ooh no, something went wrong!