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.

ecause if is a reserved word—when you try to run import if, you’ll get a syntaxerror. In fact, both the names of module files and the names of directories used inpackage imports (discussed in the next chapter) must conform to the rules forvariable names presented in Chapter 11; they may, for instance, contain only letters,digits, and underscores. Package directories also cannot contain platform-specificsyntax such as spaces in their names.When a module is imported, <strong>Python</strong> maps the internal module name to an externalfilename by adding directory paths in the module search path to the front, and a .pyor other extension at the end. For instance, a module named M ultimately maps tosome external file \M. that contains the module’s code.As mentioned in the preceding chapter, it also possible to create a <strong>Python</strong> module bywriting code in an external language such as C or C++ (or Java, in the Jython implementationof the language). Such modules are called extension modules, and they aregenerally used to wrap up external libraries for use in <strong>Python</strong> scripts. When importedby <strong>Python</strong> code, extension modules look and feel the same as modules coded as<strong>Python</strong> source code files—they are accessed with import statements, and providefunctions and objects as module attributes. Extension modules are beyond the scopeof this book; see <strong>Python</strong>’s standard manuals, or advanced texts such as Programming<strong>Python</strong> for more details.Module UsageClients can use the simple module file we just wrote by running import or from statements.Both statements find, compile, and run a module file’s code, if it hasn’t yetbeen loaded. The chief difference is that import fetches the module as a whole, soyou must qualify to fetch its names; in contrast, from fetches (or copies) specificnames out of the module.Let’s see what this means in terms of code. All of the following examples wind upcalling the printer function defined in the external module file module1.py, but indifferent ways.The import StatementIn the first example, the name module1 serves two different purposes—it identifies anexternal file to be loaded, and it becomes a variable in the script, which referencesthe module object after the file is loaded:>>> import module1 # Get module as a whole>>> module1.printer('Hello world!') # Qualify to get namesHello world!Because import gives a name that refers to the whole module object, we must gothrough the module name to fetch its attributes (e.g., module1.printer).Module Usage | 399

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

Saved successfully!

Ooh no, something went wrong!