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.

The first time this module is imported (or run as a program), <strong>Python</strong> executes itsstatements from top to bottom. Some statements create names in the module’snamespace as a side effect, but others may do actual work while the import is goingon. For instance, the two print statements in this file execute at import time:>>> import module2starting to load...done loading.But once the module is loaded, its scope becomes an attribute namespace in themodule object we get back from import. We can then access attributes in thisnamespace by qualifying them with the name of the enclosing module:>>> module2.sys>>> module2.name42>>> module2.func>>> module2.klassHere, sys, name, func, and klass were all assigned while the module’s statementswere being run, so they are attributes after the import. We’ll talk about classes inPart VI, but notice the sys attribute—import statements really assign module objectsto names, and any type of assignment to a name at the top level of a file generates amodule attribute.Internally, module namespaces are stored as dictionary objects. These are just normaldictionary objects with the usual methods. We can access a module’s namespacedictionary through the module’s _ _dict_ _ attribute:>>> module2._ _dict_ _.keys( )['__file__', 'name', '__name__', 'sys', '__doc__', '_ _builtins_ _','klass', 'func']The names we assigned in the module file become dictionary keys internally, so mostof the names here reflect top-level assignments in our file. However, <strong>Python</strong> alsoadds some names in the module’s namespace for us; for instance, _ _file_ _ gives thename of the file the module was loaded from, and _ _name_ _ gives its name as knownto importers (without the .py extension and directory path).Attribute Name QualificationNow that you’re becoming more familiar with modules, we should look at thenotion of name qualification in more depth. In <strong>Python</strong>, you can access the attributesof any object that has attributes using the qualification syntax object.attribute.406 | Chapter 19: Module Coding Basics

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

Saved successfully!

Ooh no, something went wrong!