Text stringlengths 1 9.41k |
|---|
Within mod1, mod2
is just a name that refers to an object with attributes, some of which may refer to other
objects with attributes (import is an assignment). |
For paths like mod2.mod3.X, Python
simply evaluates from left to right, fetching attributes from objects along the way.
Note that mod1 can say import mod2, and then mod2.mod3.X, but it cannot say import
```
mod2.mod3—this syntax invokes something called package (directory) imports,
```
described in the next chapter. |
Package imports also create module namespace nesting,
but their import statements are taken to reflect directory trees, not simple import chains.
###### Reloading Modules
As we’ve seen, a module’s code is run only once per process by default. |
To force a
module’s code to be reloaded and rerun, you need to ask Python to do so explicitly by
calling the reload built-in function. |
In this section, we’ll explore how to use reloads to
make your systems more dynamic. |
In a nutshell:
- Imports (via both import and from statements) load and run a module’s code only
the first time the module is imported in a process.
- Later imports use the already loaded module object without reloading or rerunning
the file’s code.
**|**
-----
- The reload function forces an already loaded mo... |
Assignments in the file’s new code change the existing module object
in-place.
Why all the fuss about reloading modules? |
The reload function allows parts of a program to be changed without stopping the whole program. With reload, therefore, the
effects of changes in components can be observed immediately. |
Reloading doesn’t help
in every situation, but where it does, it makes for a much shorter development cycle.
For instance, imagine a database program that must connect to a server on startup;
because program changes or customizations can be tested immediately after reloads,
you need to connect only once while debugging... |
Long-running servers can update
themselves this way, too.
Because Python is interpreted (more or less), it already gets rid of the compile/link steps
you need to go through to get a C program to run: modules are loaded dynamically
when imported by a running program. |
Reloading offers a further performance advantage by allowing you to also change parts of running programs without stopping.
Note that reload currently only works on modules written in Python; compiled extension modules coded in a language such as C can be dynamically loaded at runtime, too,
but they can’t be reloaded.
... |
In Python 3.0, it has been moved to the `imp standard library`
module—it’s known as imp.reload in 3.0. |
This simply means that an
extra import or from statement is required to load this tool (in 3.0 only).
Readers using 2.6 can ignore these imports in this book’s examples, or
use them anyhow—2.6 also has a reload in its imp module to ease migration to 3.0. |
Reloading works the same regardless of its packaging.
###### reload Basics
Unlike import and from:
- reload is a function in Python, not a statement.
- reload is passed an existing module object, not a name.
- reload lives in a module in Python 3.0 and must be imported itself.
Because reload expects an object,... |
Furthermore,
the syntax of import statements and reload calls differs: reloads require parentheses,
but imports do not. |
Reloading looks like this:
```
import module # Initial import
...use module.attributes...
... |
# Now, go change the module file
...
```
**|**
-----
```
from imp import reload # Get reload itself (in 3.0)
reload(module) # Get updated exports
...use module.attributes...
```
The typical usage pattern is that you import a module, then change its source code in
a text editor, and then reloa... |
When you call reload, Python rereads the module file’s
source code and reruns its top-level statements. |
Perhaps the most important thing to
know about reload is that it changes a module object in-place; it does not delete and
re-create the module object. |
Because of that, every reference to a module object anywhere in your program is automatically affected by a reload. |
Here are the details:
- reload **runs a module file’s new code in the module’s current namespace.**
Rerunning a module file’s code overwrites its existing namespace, rather than deleting and re-creating it.
- Top-level assignments in the file replace names with new values. |
For instance,
rerunning a def statement replaces the prior version of the function in the module’s
namespace by reassigning the function name.
- Reloads impact all clients that use `import` **to fetch modules. |
Because clients**
that use import qualify to fetch attributes, they’ll find new values in the module
object after a reload.
- Reloads impact future `from` **clients only. |
Clients that used from to fetch attributes**
in the past won’t be affected by a reload; they’ll still have references to the old
objects fetched before the reload.
###### reload Example
To demonstrate, here’s a more concrete example of reload in action. |
In the following,
we’ll change and reload a module file without stopping the interactive Python session.
Reloads are used in many other scenarios, too (see the sidebar “Why You Will Care:
Module Reloads” on page 557), but we’ll keep things simple for illustration here.
First, in the text editor of your choice, write a ... |
Now, start the Python interpreter, import the module, and call the function
it exports. |
The function will print the value of the global message variable:
```
% python
>>> import changer
>>> changer.printer()
First version
```
**|**
-----
Keeping the interpreter active, now edit the module file in another window:
```
...modify changer.py without stopping Python...
% vi changer.py
```
Chang... |
Notice
in the following interaction that importing the module again has no effect; we get the
original message, even though the file’s been changed. |
We have to call reload in order
to get the new version:
```
...back to the Python interpreter/program...
>>> import changer
```
`>>> changer.printer()` _# No effect: uses loaded module_
```
First version
>>> from imp import reload
```
`>>> reload(changer)` _# Forces new code to load/run_
```
<module 'change... |
For instance, systems that must connect to servers
over a network on startup are prime candidates for dynamic reloads.
They’re also useful in GUI work (a widget’s callback action can be changed while the
GUI remains active), and when Python is used as an embedded language in a C or
C++ program (the enclosing program c... |
See Programming Python for more on reloading GUI callbacks
and embedded Python code.
More generally, reloads allow programs to provide highly dynamic interfaces. |
For instance, Python is often used as a customization language for larger systems—users can
customize products by coding bits of Python code onsite, without having to recompile
the entire product (or even having its source code at all). |
In such worlds, the Python
code already adds a dynamic flavor by itself.
**|**
-----
###### Chapter Summary
This chapter delved into the basics of module coding tools—the import and from statements, and the reload call. |
We learned how the from statement simply adds an extra
step that copies names out of a file after it has been imported, and how reload forces
a file to be imported again without stopping and restarting Python. |
We also surveyed
namespace concepts, saw what happens when imports are nested, explored the way
files become module namespaces, and learned about some potential pitfalls of the
```
from statement.
```
Although we’ve already seen enough to handle module files in our programs, the next
chapter extends our coverage of th... |
As we’ll see, package imports give us a hierarchy that is useful in larger systems
and allow us to break conflicts between same-named modules. |
Before we move on,
though, here’s a quick quiz on the concepts presented here.
###### Test Your Knowledge: Quiz
1. How do you make a module?
2. |
How is the from statement related to the import statement?
3. How is the reload function related to imports?
4. When must you use import instead of from?
5. |
Name three potential pitfalls of the from statement.
6. What...is the airspeed velocity of an unladen swallow?
###### Test Your Knowledge: Answers
1. |
To create a module, you just write a text file containing Python statements; every
source code file is automatically a module, and there is no syntax for declaring one.
Import operations load module files into module objects in memory. |
You can also
make a module by writing code in an external language like C or Java, but such
extension modules are beyond the scope of this book.
**|**
-----
2. |
The from statement imports an entire module, like the import statement, but as an
extra step it also copies one or more variables from the imported module into the
scope where the from appears. |
This enables you to use the imported names directly
(name) instead of having to go through the module (module.name).
3. By default, a module is imported only once per process. |
The reload function forces
a module to be imported again. It is mostly used to pick up new versions of a
module’s source code during development, and in dynamic customization
scenarios.
4. |
You must use import instead of from only when you need to access the same name
in two different modules; because you’ll have to specify the names of the enclosing
modules, the two names will be unique.
5. |
The `from statement can obscure the meaning of a variable (which module it is`
defined in), can have problems with the reload call (names may reference prior
versions of objects), and can corrupt namespaces (it might silently overwrite names
you are using in your scope). |
The from * form is worse in most regards—it can
seriously corrupt namespaces and obscure the meaning of variables, so it is probably best used sparingly.
6. What do you mean? |
An African or European swallow?
**|**
-----
-----
###### CHAPTER 23
### Module Packages
So far, when we’ve imported modules, we’ve been loading files. |
This represents typical
module usage, and it’s probably the technique you’ll use for most imports you’ll code
early on in your Python career. |
However, the module import story is a bit richer than
I have thus far implied.
In addition to a module name, an import can name a directory path. |
A directory of
Python code is said to be a package, so such imports are known as package imports. |
In
effect, a package import turns a directory on your computer into another Python namespace, with attributes corresponding to the subdirectories and module files that the
directory contains.
This is a somewhat advanced feature, but the hierarchy it provides turns out to be handy
for organizing the files in a large sy... |
As we’ll see, package imports are also sometimes required to resolve import
ambiguities when multiple program files of the same name are installed on a single
machine.
Because it is relevant to code in packages only, we’ll also introduce Python’s recent
_relative imports model and syntax here. |
As we’ll see, this model modifies search paths_
and extends the from statement for imports within packages.
###### Package Import Basics
So, how do package imports work? |
In the place where you have been naming a simple
file in your import statements, you can instead list a path of names separated by periods:
```
import dir1.dir2.mod
```
The same goes for from statements:
```
from dir1.dir2.mod import x
```
-----
The “dotted” path in these statements is assumed to correspond to ... |
That is, the preceding statements indicate that on your machine there
is a directory _dir1, which has a subdirectory_ _dir2, which contains a module file_
_mod.py (or similar)._
Furthermore, these imports imply that dir1 resides within some container directory
_dir0, which is a component of the Python module search pa... |
In other words, the two_
```
import statements imply a directory structure that looks something like this (shown
```
with DOS backslash separators):
```
dir0\dir1\dir2\mod.py # Or mod.pyc, mod.so, etc.
```
The container directory dir0 needs to be added to your module search path (unless it’s
the home directo... |
From
there down, though, the import statements in your script give the directory paths leading to the modules explicitly.
###### Packages and Search Path Settings
If you use this feature, keep in mind that the directory paths in your import statements
can only be variables separated by periods. |
You cannot use any platform-specific path
syntax in your import statements, such as C:\dir1, My Documents.dir2 or ../dir1—these
do not work syntactically. |
Instead, use platform-specific syntax in your module search
path settings to name the container directories.
For instance, in the prior example, dir0—the directory name you add to your module
search path—can be an arbitrarily long and platform-specific directory path leading up
to dir1. |
Instead of using an invalid statement like this:
```
import C:\mycode\dir1\dir2\mod # Error: illegal syntax
```
add C:\mycode to your PYTHONPATH variable or a .pth file (assuming it is not the program’s
home directory, in which case this step is not necessary), and say this in your script:
```
import dir1.dir2.m... |
This syntax also means that you get odd error messages if you forget to omit
the .py in your import statements. |
For example, import mod.py is assumed to be a directory path import—it
loads mod.py, then tries to load a mod\py.py, and ultimately issues a potentially confusing “No module named
py” error message.
**|**
-----
###### Package __init__.py Files
If you choose to use package imports, there is one more constraint you ... |
That is, in the example we’ve
been using, both _dir1 and_ _dir2 must contain a file called_ ___init__.py; the container_
directory dir0 does not require such a file because it’s not listed in the import statement
itself. |
More formally, for a directory structure such as this:
```
dir0\dir1\dir2\mod.py
```
and an import statement of the form:
```
import dir1.dir2.mod
```
the 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 ... |
They are
partly present as a declaration to Python, however, and can be completely empty. |
As
declarations, these files serve to prevent directories with common names from unintentionally hiding true modules that appear later on the module search path. |
Without
this safeguard, Python might pick a directory that has nothing to do with your 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-time actions, generates a module namespace for a directory, and implements th... |
import *) statements when used with directory imports:
```
_Package initialization_
The first time Python imports through a directory, it automatically runs all the code
in the directory’s __init__.py file. |
Because of that, these files are a natural place to
put code to initialize the state required by files in a package. |
For instance, a package
might use its initialization file to create required data files, open connections to
**|**
-----
databases, and so on. |
Typically, __init__.py files are not meant to be useful if executed directly; they are run automatically when a package is first accessed.
_Module namespace initialization_
In the package import model, the directory paths in your script become real nested
object paths after an import. |
For instance, in the preceding example, after the import the expression dir1.dir2 works and returns a module object whose namespace
contains all the names assigned by _dir2’s_ ___init__.py file. |
Such files provide a_
namespace for module objects created for directories, which have no real associated module files.
```
from * statement behavior
```
As an advanced feature, you can use __all__ lists in __init__.py files to define what
is exported when a directory is imported with the from * statement form. |
In an
___init__.py file, the __all__ list is taken to be the list of submodule names that_
should be imported when `from * is used on the package (directory) name. |
If`
```
__all__ is not set, the from * statement does not automatically load submodules
```
nested in the directory; instead, it loads just names defined by assignments in the
directory’s __init__.py file, including any submodules explicitly imported by code
in this file. |
For instance, the statement from submodule import X in a directory’s
___init__.py makes the name X available in that directory’s namespace. |
(We’ll see_
additional roles for __all__ in Chapter 24.)
You can also simply leave these files empty, if their roles are beyond your needs (and
frankly, they are often empty in practice). |
They must exist, though, for your directory
imports to work at all.
Don’t confuse package ___init__.py files with the class_ `__init__ con-`
structor methods we’ll meet in the next part of the book. |
The former
are files of code run when imports first step through a package directory,
while the latter are called when an instance is created. |
Both have initialization roles, but they are otherwise very different.
###### Package Import Example
Let’s actually code the example we’ve been talking about to show how initialization
files and paths come into play. |
The following three files are coded in a directory dir1
and its subdirectory dir2—comments give the path names of these files:
_# dir1\__init__.py_
```
print('dir1 init')
x = 1
```
_# dir1\dir2\__init__.py_
```
print('dir2 init')
y = 2
```
**|**
-----
_# dir1\dir2\mod.py_
```
print('in mod.py')
z = 3
... |
Either way, dir1’s container does not need an __init__.py file.
```
import statements run each directory’s initialization file the first time that directory is
```
traversed, as Python descends the path; `print statements are included here to trace`
their execution. |
As with module files, an already imported directory may be passed to
```
reload to force reexecution of that single item. |
As shown here, reload accepts a dotted
```
pathname to reload nested directories and files:
```
% python
```
`>>> import dir1.dir2.mod` _# First imports run init files_
```
dir1 init
dir2 init
in mod.py
>>>
```
`>>> import dir1.dir2.mod` _# Later imports do not_
```
>>>
```
`>>> from imp import reload` ... |
Here, mod is an object nested in the object dir2, which in turn is nested in the
object dir1:
```
>>> dir1
<module 'dir1' from 'dir1\__init__.pyc'>
>>> dir1.dir2
<module 'dir1.dir2' from 'dir1\dir2\__init__.pyc'>
>>> dir1.dir2.mod
<module 'dir1.dir2.mod' from 'dir1\dir2\mod.pyc'>
```
In fact, each director... |
dir1.x refers to the variable x assigned in dir1\__init__.py, much as mod.z refers to
the variable z assigned in mod.py:
```
>>> dir1.x
1
>>> dir1.dir2.y
2
>>> dir1.dir2.mod.z
3
```
**|**
-----
###### from Versus import with Packages
```
import statements can be somewhat inconvenient to use with package... |
In the prior section’s example,
for instance, you must retype and rerun the full path from dir1 each time you want to
reach z. |
If you try to access dir2 or mod directly, you’ll get an error:
```
>>> dir2.mod
NameError: name 'dir2' is not defined
>>> mod.z
NameError: name 'mod' is not defined
```
It’s often more convenient, therefore, to use the from statement with packages to avoid
retyping the paths at each access. |
Perhaps more importantly, if you ever restructure
your directory tree, the `from statement requires just one path update in your code,`
whereas imports may require many. |
The import as extension, discussed formally in the
next chapter, can also help here by providing a shorter synonym for the full path:
```
% python
```
`>>> from dir1.dir2 import mod` _# Code path here only_
```
dir1 init
dir2 init
in mod.py
```
`>>> mod.z` _# Don't repeat path_
```
3
>>> from dir1.dir2.mo... |
They do serve useful
roles, though, especially in larger programs: they make imports more informative, serve
as an organizational tool, simplify your module search path, and can resolve
ambiguities.
First of all, because package imports give some directory information in program files,
they both make it easier to loca... |
Without
package paths, you must often resort to consulting the module search path to find files.
Moreover, if you organize your files into subdirectories for functional areas, package
imports make it more obvious what role a module plays, and so make your code more
readable. |
For example, a normal import of a file in a directory somewhere on the module
search path, like this:
```
import utilities
```
**|**
-----
offers much less information than an import that includes the path:
```
import database.client.utilities
```
Package imports can also greatly simplify your `PYTHONPATH and`... |
In fact, if you use explicit package imports for all your cross-directory imports,
and you make those package imports relative to a common root directory where all
your Python code is stored, you really only need a single entry on your search path: the
common root. |
Finally, package imports serve to resolve ambiguities by making explicit
exactly which files you want to import. |
The next section explores this role in more
detail.
###### A Tale of Three Systems
The only time package imports are actually required is to resolve ambiguities that may
arise when multiple programs with same-named files are installed on a single machine.
This is something of an install issue, but it can also become ... |
All over this program, its files say import utilities to load and
use the common code. |
When the program is shipped, it arrives as a single .tar or .zip
file containing all the program’s files, and when it is installed, it unpacks all its files into
a single directory named system1 on the target machine:
```
system1\
utilities.py # Common utility functions, classes
main.py # Launch this... |
When this second system is fetched and installed
on the same computer as the first system, its files will unpack into a new directory called
_system2 somewhere on the receiving machine (ensuring that they do not overwrite_
same-named files from the first system):
```
system2\
utilities.py # Common utilities
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.