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.

in the next chapter, can also help here by providing a shorter synonym for the fullpath:% python>>> from dir1.dir2 import mod # Code path here onlydir1 initdir2 initin mod.py>>> mod.z # Don't repeat path3>>> from dir1.dir2.mod import z>>> z3>>> import dir1.dir2.mod as mod # Use shorter name>>> mod.z3Why Use Package Imports?If you’re new to <strong>Python</strong>, make sure that you’ve mastered simple modules before steppingup to packages, as they are a somewhat advanced feature. They do serve usefulroles, though, especially in larger programs: they make imports more informative,serve as an organizational tool, simplify your module search path, and can resolveambiguities.First of all, because package imports give some directory information in programfiles, they both make it easier to locate your files and serve as an organizational tool.Without package paths, you must often resort to consulting the module search pathto find files. Moreover, if you organize your files into subdirectories for functionalareas, package imports make it more obvious what role a module plays, and so makeyour code more readable. For example, a normal import of a file in a directory somewhereon the module search path, like this:import utilitiesoffers much less information than an import that includes the path:import database.client.utilitiesPackage imports can also greatly simplify your PYTHONPATH and .pth file search pathsettings. In fact, if you use package imports for all your cross-directory imports, andyou make those package imports relative to a common root directory, where all your<strong>Python</strong> code is stored, you really only need a single entry on your search path: thecommon root. Finally, package imports serve to resolve ambiguities by makingexplicit exactly which files you want to import. The next section explores this role inmore detail.420 | Chapter 20: Module Packages

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

Saved successfully!

Ooh no, something went wrong!