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.

Now the problem starts to materialize. To make this work at all, you’ll have to setthe module search path to include the directories containing the utilities.py files. Butwhich directory do you put first in the path—system1 or system2?The problem is the linear nature of the search path. It is always scanned from left toright, so no matter how long you ponder this dilemma, you will always get utilities.pyfrom the directory listed first (leftmost) on the search path. As is, you’ll never be ableto import it from the other directory at all. You could try changing sys.path withinyour script before each import operation, but that’s both extra work, and highlyerror-prone. By default, you’re stuck.This is the issue that packages actually fix. Rather than installing programs as flatlists of files in standalone directories, you can package and install them as subdirectoriesunder a common root. For instance, you might organize all the code in thisexample as an install hierarchy that looks like this:root\system1\_ _init_ _.pyutilities.pymain.pyother.pysystem2\_ _init_ _.pyutilities.pymain.pyother.pysystem3\# Here or elsewhere_ _init_ _.py # Your new code heremyfile.pyNow, add just the common root directory to your search path. If your code’s importsare all relative to this common root, you can import either system’s utility file with apackage import—the enclosing directory name makes the path (and hence, the modulereference) unique. In fact, you can import both utility files in the same module, aslong as you use an import statement, and repeat the full path each time you referencethe utility modules:import system1.utilitiesimport system2.utilitiessystem1.utilities.function('spam')system2.utilities.function('eggs')The name of the enclosing directory here makes the module references unique.Note that you have to use import instead of from with packages only if you need toaccess the same attribute in two or more paths. If the name of the called functionhere was different in each path, from statements could be used to avoid repeating thefull package path whenever you call one of the functions, as described earlier.422 | Chapter 20: Module Packages

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

Saved successfully!

Ooh no, something went wrong!