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.

dir0\dir1\dir2\mod.pyand an import statement of the form:import dir1.dir2.modthe following rules apply:• dir1 and dir2 both must contain an _ _init_ _.py file.• dir0, the container, does not require an _ _init_ _.py file; this file will simply beignored if present.• dir0, not dir0\dir1, must be listed on the module search path (i.e., it must be thehome directory, or be listed in your PYTHONPATH, etc.).The net effect is that this example’s directory structure should be as follows, withindentation designating directory nesting:dir0\dir1\_ _init_ _.pydir2\_ _init_ _.pymod.py# Container on module search pathThe _ _init_ _.py files can contain <strong>Python</strong> code, just like normal module files. Theyare partly present as a declaration to <strong>Python</strong>, however, and can be completely empty.As declarations, these files serve to prevent directories with common names fromunintentionally hiding true modules that appear later on the module search path.Without this safeguard, <strong>Python</strong> might pick a directory that has nothing to do withyour code, just because it appears in an earlier directory on the search path.More generally, the _ _init_ _.py file serves as a hook for package initialization-timeactions, generates a module namespace for a directory, and implements the behaviorof from * (i.e., from ... import *) statements when used with directory imports:Package initializationThe first time <strong>Python</strong> imports through a directory, it automatically runs all thecode in the directory’s _ _init_ _.py file. Because of that, these files are a naturalplace to put code to initialize the state required by files in the package. Forinstance, a package might use its initialization file to create required data files,open connections to databases, and so on. Typically, _ _init_ _.py files are notmeant to be useful if executed directly; they are run automatically when a packageis first accessed.Module namespace initializationIn the package import model, the directory paths in your script become realnested object paths after an import. For instance, in the preceding example, afterthe import, the expression dir1.dir2 works and returns a module object whosenamespace contains all the names assigned by dir2’s _ _init_ _.py file. Such filesprovide a namespace for module objects created for directories, which have noreal associated module files.Package Import Basics | 417

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

Saved successfully!

Ooh no, something went wrong!