Text
stringlengths
1
9.41k
Any file can import tools from any other file. For instance, the file a.py may import b.py to call its function, but b.py might also import c.py to leverage different tools defined there.
Import chains can go as deep as you like: in this example, the module a can import b, which can import c, which can import b again, and so on. Besides serving as the highest organizational structure, modules (and module packages, described in Chapter 23) are also the highest level of _code reuse in Python.
Coding_ components in module files makes them useful in your original program, and in any other programs you may write.
For instance, if after coding the program in Figure 21-1 we discover that the function b.spam is a general-purpose tool, we can reuse **|** ----- it in a completely different program; all we have to do is import the file b.py again from the other program’s files. ###### Standard Library Modules Notice the rightmo...
Some of the modules that your programs will import are provided by Python itself and are not files you will code. Python automatically comes with a large collection of utility modules known as the _standard library.
This collection, roughly 200 modules large at last count, contains_ platform-independent support for common programming tasks: operating system interfaces, object persistence, text pattern matching, network and Internet scripting, GUI construction, and much more.
None of these tools are part of the Python language itself, but you can use them by importing the appropriate modules on any standard Python installation.
Because they are standard library modules, you can also be reasonably sure that they will be available and will work portably on most platforms on which you will run Python. You will see a few of the standard library modules in action in this book’s examples, but for a complete look you should browse the standard Pyth...
You can also find tutorials on Python library tools in commercial books that cover application-level programming, such as O’Reilly’s Programming Py _thon, but the manuals are free, viewable in any web browser (they ship in HTML for-_ mat), and updated each time Python is rereleased. ###### How Imports Work The prior ...
Because imports are at the heart of program structure in Python, this section goes into more detail on the import operation to make this process less abstract. Some C programmers like to compare the Python module import operation to a `C` ``` #include, but they really shouldn’t—in Python, imports are not just textual ...
They are really runtime operations that perform three distinct steps the first time a program imports a given file: 1. Find the module’s file. 2. Compile it to byte code (if needed). 3.
Run the module’s code to build the objects it defines. **|** ----- To better understand module imports, we’ll explore these steps in turn.
Bear in mind that all three of these steps are carried out only the first time a module is imported during a program’s execution; later imports of the same module bypass all of these steps and simply fetch the already loaded module object in memory.
Technically, Python does this by storing loaded modules in a table named sys.modules and checking there at the start of an import operation.
If the module is not present, a three-step process begins. ###### 1. Find It First, Python must locate the module file referenced by an import statement.
Notice that the import statement in the prior section’s example names the file without a .py suffix and without its directory path: it just says import b, instead of something like ``` import c:\dir1\b.py.
In fact, you can only list a simple name; path and suffix details ``` are omitted on purpose and Python uses a standard module search path to locate the module file corresponding to an import statement.[*] Because this is the main part of the import operation that programmers must know about, we’ll return to this topi...
Compile It (Maybe) After finding a source code file that matches an `import statement by traversing the` module search path, Python next compiles it to byte code, if necessary.
(We discussed byte code in Chapter 2.) Python checks the file timestamps and, if the byte code file is older than the source file (i.e., if you’ve changed the source), automatically regenerates the byte code when the program is run.
If, on the other hand, it finds a .pyc byte code file that is not older than the corresponding _.py source file, it skips the source-to–byte code compile step.
In_ addition, if Python finds only a byte code file on the search path and no source, it simply loads the byte code directly (this means you can ship a program as just byte code files and avoid sending source).
In other words, the compile step is bypassed if possible to speed program startup. Notice that compilation happens when a file is being imported.
Because of this, you will not usually see a .pyc byte code file for the top-level file of your program, unless it is also imported elsewhere—only imported files leave behind _.pyc files on your_ - It’s actually syntactically illegal to include path and suffix details in a standard import.
Package imports, which we’ll discuss in Chapter 23, allow import statements to include part of the directory path leading to a file as a set of period-separated names; however, package imports still rely on the normal module search path to locate the leftmost directory in a package path (i.e., they are relative to a di...
They also cannot make use of any platform-specific directory syntax in the import statements; such syntax only works on the search path.
Also, note that module file search path issues are not as relevant when you run _frozen executables (discussed in Chapter 2); they typically embed byte code in the binary image._ **|** ----- machine.
The byte code of top-level files is used internally and discarded; byte code of imported files is saved in files to speed future imports. Top-level files are often designed to be executed directly and not imported at all.
Later, we’ll see that it is possible to design a file that serves both as the top-level code of a program and as a module of tools to be imported.
Such a file may be both executed and imported, and thus does generate a .pyc. To learn how this works, watch for the discussion of the special __name__ attribute and __main__ in Chapter 24. ###### 3.
Run It The final step of an import operation executes the byte code of the module.
All statements in the file are executed in turn, from top to bottom, and any assignments made to names during this step generate attributes of the resulting module object.
This execution step therefore generates all the tools that the module’s code defines.
For instance, ``` def statements in a file are run at import time to create functions and assign attributes ``` within the module to those functions.
The functions can then be called later in the program by the file’s importers. Because this last import step actually runs the file’s code, if any top-level code in a module file does real work, you’ll see its results at import time.
For example, top-level ``` print statements in a module show output when the file is imported.
Function def ``` statements simply define objects for later use. As you can see, import operations involve quite a bit of work—they search for files, possibly run a compiler, and run Python code.
Because of this, any given module is imported only once per process by default. Future imports skip all three import steps and reuse the already loaded module in memory.
If you need to import a file again after it has already been loaded (for example, to support end-user customization), you have to force the issue with an imp.reload call—a tool we’ll meet in the next chapter.[†] ###### The Module Search Path As mentioned earlier, the part of the import procedure that is most importan...
Because you may need to tell Python where to look to find files to import, you need to know how to tap into its search path in order to extend it. † As described earlier, Python keeps already imported modules in the built-in sys.modules dictionary so it can keep track of what’s been loaded.
In fact, if you want to see which modules are loaded, you can import sys and print list(sys.modules.keys()).
More on other uses for this internal table in Chapter 24. **|** ----- In many cases, you can rely on the automatic nature of the module import search path and won’t need to configure this path at all.
If you want to be able to import files across directory boundaries, though, you will need to know how the search path works in order to customize it.
Roughly, Python’s module search path is composed of the concatenation of these major components, some of which are preset for you and some of which you can tailor to tell Python where to look: 1.
The home directory of the program 2. PYTHONPATH directories (if set) 3. Standard library directories 4.
The contents of any .pth files (if present) Ultimately, the concatenation of these four components becomes sys.path, a list of directory name strings that I’ll expand upon later in this section.
The first and third elements of the search path are defined automatically.
Because Python searches the concatenation of these components from first to last, though, the second and fourth elements can be used to extend the path to include your own source code directories. Here is how Python uses each of these path components: _Home directory_ Python first looks for the imported file in the ho...
The meaning of this entry depends on how you are running the code. When you’re running a program, this entry is the directory containing your program’s top-level script file.
When you’re working interactively, this entry is the directory in which you are working (i.e., the current working directory). Because this directory is always searched first, if a program is located entirely in a single directory, all of its imports will work automatically with no path configuration required.
On the other hand, because this directory is searched first, its files will also override modules of the same name in directories elsewhere on the path; be careful not to accidentally hide library modules this way if you need them in your program. ``` PYTHONPATH directories ``` Next, Python searches all directories li...
In brief, ``` PYTHONPATH is simply set to a list of user-defined and platform-specific names of ``` directories that contain Python code files.
You can add all the directories from which you wish to be able to import, and Python will extend the module search path to include all the directories your PYTHONPATH lists. Because Python searches the home directory first, this setting is only important when importing files across directory boundaries—that is, if you ...
You’ll probably want to set your PYTHONPATH variable once you start writing substantial programs, but when you’re first starting out, as long as you save all your module files in the **|** ----- directory in which you’re working (i.e., the home directory, described earlier) your imports will work without you needin...
Because these are always searched, they normally do not need to be added to your `PYTHONPATH or included in path files` (discussed next). _.pth path file directories_ Finally, a lesser-used feature of Python allows users to add directories to the module search path by simply listing them, one per line, in a text file w...
These path configuration files are a somewhat advanced installation-related feature; we won’t them cover fully here, but they provide an alternative to PYTHONPATH settings. In short, text files of directory names dropped in an appropriate directory can serve roughly the same role as the PYTHONPATH environment variable ...
For instance, if you’re running Windows and Python 3.0, a file named _myconfig.pth may be_ placed at the top level of the Python install directory (C:\Python30) or in the site_packages subdirectory of the standard library there (C:\Python30\Lib\site-_ _packages) to extend the module search path.
On Unix-like systems, this file might_ be located in _usr/local/lib/python3.0/site-packages or_ _/usr/local/lib/site-python_ instead. When present, Python will add the directories listed on each line of the file, from first to last, near the end of the module search path list.
In fact, Python will collect the directory names in all the path files it finds and will filter out any duplicates and nonexistent directories.
Because they are files rather than shell settings, path files can apply to all users of an installation, instead of just one user or shell.
Moreover, for some users text files may be simpler to code than environment settings. This feature is more sophisticated than I’ve described here.
For more details consult the Python library manual, and especially its documentation for the standard library module site—this module allows the locations of Python libraries and path files to be configured, and its documentation describes the expected locations of path files in general.
I recommend that beginners use PYTHONPATH or perhaps a single .pth file, and then only if you must import across directories.
Path files are used more often by third-party libraries, which commonly install a path file in Python’s _site-packages directory so that user settings are not required (Python’s distutils_ install system, described in an upcoming sidebar, automates many install steps). ###### Configuring the Search Path The net effec...
The way you set environment variables and where you store path files varies per platform.
For instance, **|** ----- on Windows, you might use your Control Panel’s System icon to set PYTHONPATH to a list of directories separated by semicolons, like this: ``` c:\pycode\utilities;d:\pycode\package1 ``` Or you might instead create a text file called C:\Python30\pydirs.pth, which looks like this: ``` c:...
See Appendix A for pointers on extending your module search path with PYTHONPATH or .pth files on various platforms. ###### Search Path Variations This description of the module search path is accurate, but generic; the exact configuration of the search path is prone to changing across platforms and Python releases. ...
When you’re launching from a command line, the current working directory may not be the same as the home directory of your top-level file (i.e., the directory where your program file resides).
Because the current working directory can vary each time your program runs, you normally shouldn’t depend on its value for import purposes.
See Chapter 3 for more on launching programs from command lines.[‡] To see how your Python configures the module search path on your platform, you can always inspect sys.path—the topic of the next section. ###### The sys.path List If you want to see how the module search path is truly configured on your machine, you...
This list of directory name strings is the actual search path within Python; on imports, Python searches each directory in this list from left to right. ‡ See also Chapter 23’s discussion of the new relative import syntax in Python 3.0; this modifies the search path for from statements in files inside packages when “....
import string). By default, a package’s own directory is not automatically searched by imports in Python 3.0, unless relative imports are used by files in the package itself. **|** ----- Really, sys.path _is the module search path.
Python configures it at program startup,_ automatically merging the home directory of the top-level file (or an empty string to designate the current working directory), any PYTHONPATH directories, the contents of any .pth file paths you’ve created, and the standard library directories.
The result is a list of directory name strings that Python searches on each import of a new file. Python exposes this list for two good reasons.
First, it provides a way to verify the search path settings you’ve made—if you don’t see your settings somewhere in this list, you need to recheck your work.
For example, here is what my module search path looks like on Windows under Python 3.0, with my `PYTHONPATH set to` `C:\users and a` _C:\Python30\mypath.py path file that lists C:\users\mark.
The empty string at the front_ means current directory and my two settings are merged in (the rest are standard library directories and files): ``` >>> import sys >>> sys.path ['', 'C:\\users', 'C:\\Windows\\system32\\python30.zip', 'c:\\Python30\\DLLs', 'c:\\Python30\\lib', 'c:\\Python30\\lib\\plat-win', 'c:\\...
As you’ll see later in this part of the book, by modifying the ``` sys.path list, you can modify the search path for all future imports.
Such changes only ``` last for the duration of the script, however; PYTHONPATH and .pth files offer more permanent ways to modify the path.[§] ###### Module File Selection Keep in mind that filename suffixes (e.g., .py) are intentionally omitted from import statements.
Python chooses the first file it can find on the search path that matches the imported name.
For example, an import statement of the form import b might load: - A source code file named b.py - A byte code file named b.pyc - A directory named b, for package imports (described in Chapter 23) - A compiled extension module, usually coded in C or C++ and dynamically linked when imported (e.g., b.so on Linux...
Scripts that run on web servers, for example, often run as the user “nobody” to limit machine access.
Because such scripts cannot usually depend on “nobody” to have set PYTHONPATH in any particular way, they often set sys.path manually to include required source directories, prior to running any import statements.
A sys.path.append(dirname) will often suffice. **|** ----- - A Java class, in the Jython version of Python - A .NET component, in the IronPython version of Python C extensions, Jython, and package imports all extend imports beyond simple files.
To importers, though, differences in the loaded file type are completely transparent, both when importing and when fetching module attributes.
Saying import b gets whatever module b is, according to your module search path, and b.attr fetches an item in the module, be it a Python variable or a linked-in C function.
Some standard modules we will use in this book are actually coded in C, not Python; because of this transparency, their clients don’t have to care. If you have both a b.py and a b.so in different directories, Python will always load the one found in the first (leftmost) directory of your module search path during the ...
But what happens if it finds both a b.py and a b.so in the _same directory? In this case, Python follows a standard picking order, though this order_ is not guaranteed to stay the same over time.
In general, you should not depend on which type of file Python will choose within a given directory—make your module names distinct, or configure your module search path to make your module selection preferences more obvious. ###### Advanced Module Selection Concepts Normally, imports work as described in this sectio...
However, it is possible to redefine much of what an import operation does in Python, using what are known as import hooks.
These hooks can be used to make imports do various useful things, such as loading files from archives, performing decryption, and so on. In fact, Python itself makes use of these hooks to enable files to be directly imported from ZIP archives: archived files are automatically extracted at import time when a .zip file ...
One of the standard library directories in the earlier sys.path display, for example, is a .zip file today.
For more details, see the Python standard library manual’s description of the built-in ``` __import__ function, the customizable tool that import statements actually run. ``` Python also supports the notion of .pyo optimized byte code files, created and run with the `-O Python command-line flag; because these run only...
The Psyco system (see Chapter 2) provides more substantial speedups. ###### Third-Party Software: distutils This chapter’s description of module search path settings is targeted mainly at userdefined source code that you write on your own.
Third-party extensions for Python typically use the distutils tools in the standard library to automatically install themselves, so no path configuration is required to use their code. **|** ----- ###### Chapter Summary In this chapter, we covered the basics of modules, attributes, and imports and explored the ope...
We learned that imports find the designated file on the module search path, compile it to byte code, and execute all of its statements to generate its contents.
We also learned how to configure the search path to be able to import from directories other than the home directory and the standard library directories, primarily with PYTHONPATH settings. As this chapter demonstrated, the import operation and modules are at the heart of program architecture in Python.
Larger programs are divided into multiple files, which are linked together at runtime by imports.
Imports in turn use the module search path to locate files, and modules define attributes for external use. Of course, the whole point of imports and modules is to provide a structure to your program, which divides its logic into self-contained software components.
Code in one module is isolated from code in another; in fact, no file can ever see the names defined in another, unless explicit import statements are run.
Because of this, modules minimize name collisions between different parts of your program. You’ll see what this all means in terms of actual statements and code in the next chapter. Before we move on, though, let’s run through the chapter quiz. ###### Test Your Knowledge: Quiz 1.