Text stringlengths 1 9.41k |
|---|
import string # <== Fails if no string.py here!
C:\test> C:\python30\python
>>> import pkg.spam
...text omitted...
ImportError: cannot import name string
```
Modules referenced by relative imports must exist in the package directory.
###### Imports are still relative to the CWD (again)
Although absolute... |
For one last test, let’s define two string modules of our own. |
In
the following, there is one module by that name in the CWD, one in the package, and
another in the standard library:
_# test\string.py_
```
print('string' * 8)
```
_# test\pkg\spam.py_
```
from . |
import string # <== Relative in both 2.6 and 3.0
print(string)
```
_# test\pkg\string.py_
```
print('Ni' * 8)
```
When we import the string module with relative import syntax, we get the version in
the package, as desired:
`C:\test> c:\Python30\python` _# Same result in 2.6_
```
>>> import pkg.spam
NiNi... |
2.6
interprets this as relative to the package, but 3.0 makes it “absolute,” which in this case
really just means it skips the package and loads the version relative to the CWD (not
the version the standard library):
_# test\string.py_
```
print('string' * 8)
```
**|**
-----
_# test\pkg\spam.py_
```
import str... |
In this case, a file in the program using the package hides the standard
library module the package may want. |
All that the change in 3.0 really accomplishes is
allowing package code to select files either inside or outside the package (i.e., relatively
or absolutely). |
Because import resolution can depend on an enclosing context that may
not be foreseen, absolute imports in 3.0 are not a guarantee of finding a module in the
standard library.
Experiment with these examples on your own for more insight. |
In practice, this is not
usually as ad-hoc as it might seem: you can generally structure your imports, search
paths, and module names to work the way you wish during development. |
You should
keep in mind, though, that imports in larger systems may depend upon context of use,
and the module import protocol is part of a successful library’s design.
Now that you’ve learned about package-relative imports, also keep in
mind that they may not always be your best option. |
Absolute package
imports, relative to a directory on sys.path, are still sometimes preferred
over both implicit package-relative imports in Python 2, and explicit
package-relative import syntax in both Python 2 and 3.
Package-relative import syntax and Python 3.0’s new absolute import
search rules at least require rel... |
Files that use imports with dots, though, are implicitly bound to a package directory and
cannot be used elsewhere without code changes.
Naturally, the extent to which this may impact your modules can vary
per package; absolute imports may also require changes when directories are reorganized.
**|**
-----
###### C... |
Package imports
are still relative to a directory on your module import search path, but rather than
relying on Python to traverse the search path manually, your script gives the rest of the
path to the module explicitly.
As we’ve seen, packages not only make imports more meaningful in larger systems, but
also simplif... |
As usual, though,
we’ll close out this chapter with a short quiz to test what you’ve learned here.
###### Test Your Knowledge: Quiz
1. |
What is the purpose of an __init__.py file in a module package directory?
2. How can you avoid repeating the full package path every time you reference a
package’s content?
3. |
Which directories require __init__.py files?
4. When must you use import instead of from with packages?
5. What is the difference between from mypkg import spam and from . |
import spam?
###### Test Your Knowledge: Answers
1. |
The __init__.py file serves to declare and initialize a module package; Python automatically runs its code the first time you import through a directory in a process.
Its assigned variables become the attributes of the module object created in memory
to correspond to that directory. |
It is also not optional—you can’t import through
a directory with package syntax unless it contains this file.
2. |
Use the from statement with a package to copy names out of the package directly,
or use the as extension with the import statement to rename the path to a shorter
synonym. |
In both cases, the path is listed in only one place, in the from or import
statement.
3. Each directory listed in an import or from statement must contain an __init__.py
file. |
Other directories, including the directory containing the leftmost component
of a package path, do not need to include this file.
4. |
You must use import instead of from with packages only if you need to access the
same name defined in more than one path. |
With import, the path makes the references unique, but from allows only one version of any given name.
5. |
from mypkg import spam is an _absolute import—the search for_ `mypkg skips the`
package directory and the module is located in an absolute directory in sys.path.
A statement from . |
import spam, on the other hand, is a relative import—spam is
looked up relative to the package in which this statement is contained before
```
sys.path is searched.
```
**|**
-----
###### CHAPTER 24
### Advanced Module Topics
This chapter concludes this part of the book with a collection of more advanced
module-... |
Like functions, modules are more effective when their
interfaces are well defined, so this chapter also briefly reviews module design concepts,
some of which we have explored in prior chapters.
Despite the word “advanced” in this chapter’s title, this is also something of a grab bag
of additional module topics. |
Because some of the topics discussed here are widely used
(especially the __name__ trick), be sure to take a look before moving on to classes in the
next part of the book.
###### Data Hiding in Modules
As we’ve seen, a Python module exports all the names assigned at the top level of its
file. |
There is no notion of declaring which names should and shouldn’t be visible outside the module. |
In fact, there’s no way to prevent a client from changing names inside
a module if it wants to.
In Python, data hiding in modules is a convention, not a syntactical constraint. |
If you
want to break a module by trashing its names, you can, but fortunately, I’ve yet to meet
a programmer who would. |
Some purists object to this liberal attitude toward data
hiding, claiming that it means Python can’t implement encapsulation. |
However, encapsulation in Python is more about packaging than about restricting.
-----
###### Minimizing from * Damage: _X and __all__
As a special case, you can prefix names with a single underscore (e.g., _X) to prevent
them from being copied out when a client imports a module’s names with a from *
statement. |
This really is intended only to minimize namespace pollution; because from
```
* copies out all names, the importer may get more than it’s bargained for (including
```
names that overwrite names in the importer). |
Underscores aren’t “private” declarations: you can still see and change such names with other import forms, such as the
```
import statement.
```
Alternatively, you can achieve a hiding effect similar to the _X naming convention by
assigning a list of variable name strings to the variable __all__ at the top level of t... |
For example:
```
__all__ = ["Error", "encode", "decode"] # Export these only
```
When this feature is used, the from * statement will copy out only those names listed
in the __all__ list. |
In effect, this is the converse of the _X convention: __all__ identifies
names to be copied, while _X identifies names not to be copied. |
Python looks for an
```
__all__ list in the module first; if one is not defined, from * copies all names without
```
a single leading underscore.
Like the _X convention, the __all__ list has meaning only to the from * statement form
and does not amount to a privacy declaration. |
Module writers can use either trick to
implement modules that are well behaved when used with from *. |
(See also the discussion of `__all__ lists in package` ___init__.py files in_ Chapter 23; there, these lists
declare submodules to be loaded for a from *.)
###### Enabling Future Language Features
Changes to the language that may potentially break existing code are introduced gradually. |
Initially, they appear as optional extensions, which are disabled by default. |
To
turn on such extensions, use a special import statement of this form:
```
from __future__ import featurename
```
This statement should generally appear at the top of a module file (possibly after a
docstring), because it enables special compilation of code on a per-module basis. |
It’s
also possible to submit this statement at the interactive prompt to experiment with
upcoming language changes; the feature will then be available for the rest of the interactive session.
For example, in prior editions of this book, we had to use this statement form to demonstrate generator functions, which requir... |
We also used this statement to activate
3.0 true division in Chapter 5, 3.0 print calls in Chapter 11, and 3.0 absolute imports
for packages in Chapter 23.
**|**
-----
All of these changes have the potential to break existing code in Python 2.6, so they are
being phased in gradually as optional features enabled wit... |
Each module has a built-in attribute called __name__,
which Python sets automatically as follows:
- If the file is being run as a top-level program file, `__name__ is set to the string`
```
"__main__" when it starts.
```
- If the file is being imported instead, __name__ is set to the module’s name as known
by its... |
For example, suppose we create the following module file, named
_runme.py, to export a single function called tester:_
```
def tester():
print("It's Christmas in Heaven...")
if __name__ == '__main__': # Only when run
tester() # Not when imported
```
This module defines a function for clien... |
Though simple, you’ll
see this hook used in nearly every realistic Python program file you are likely to
encounter.
Perhaps the most common way you’ll see the __name__ test applied is for self-test code.
In short, you can package code that tests a module’s exports in the module itself by
wrapping it in a __name__ test... |
This way, you can use the file
in clients by importing it, but also test its logic by running it from the system shell or
via another launching scheme. |
In practice, self-test code at the bottom of a file under
the __name__ test is probably the most common and simplest unit-testing protocol in
Python. |
(Chapter 35 will discuss other commonly used options for testing Python
**|**
-----
code—as you’ll see, the unittest and doctest standard library modules provide more
advanced testing tools.)
The __name__ trick is also commonly used when writing files that can be used both as
command-line utilities and as tool lib... |
For instance, suppose you write a file-finder
script in Python. |
You can get more mileage out of your code if you package it in functions and add a __name__ test in the file to automatically call those functions when the
file is run standalone. |
That way, the script’s code becomes reusable in other programs.
###### Unit Tests with __name__
In fact, we’ve already seen a prime example in this book of an instance where the
```
__name__ check could be useful. |
In the section on arguments in Chapter 18, we coded
```
a script that computed the minimum value from the set of arguments sent in:
```
def minmax(test, *args):
res = args[0]
for arg in args[1:]:
if test(arg, res):
res = arg
return res
def lessthan(x, y): return x < y
def grtrthan(x, y)... |
The problem
with the way it is currently coded, however, is that the output of the self-test call will
appear every time this file is imported from another file to be used as a tool—not exactly
a user-friendly feature! |
To improve it, we can wrap up the self-test call in a __name__
check, so that it will be launched only when the file is run as a top-level script, not when
it is imported:
```
print('I am:', __name__)
def minmax(test, *args):
res = args[0]
for arg in args[1:]:
if test(arg, res):
res = arg
... |
Python creates
and assigns this usage-mode variable as soon as it starts loading a file. |
When we run
this file as a top-level script, its name is set to __main__, so its self-test code kicks in
automatically:
```
% python min.py
I am: __main__
1
6
```
But, if we import the file, its name is not __main__, so we must explicitly call the function
to make it run:
```
>>> import min
I am: min
>>>... |
The following module, formats.py, defines string
```
formatting utilities for importers, but also checks its name to see if it is being run as a
top-level script; if so, it tests and uses arguments listed on the system command line to
run a canned or passed-in test. |
In Python, the `sys.argv list contains` _command-line_
_arguments—it is a list of strings reflecting words typed on the command line, where_
the first item is always the name of the script being run:
```
"""
Various specialized string display formatting utilities.
Test me with canned self-test or command-line arg... |
When run directly, it tests itself as
before, but it uses options on the command line to control the test behavior. |
Run this
file directly with no command-line arguments on your own to see what its self-test code
prints. |
To test specific strings, pass them in on the command line along with a minimum
field width:
```
C:\misc> python formats.py 999999999 0
$999,999,999.00
C:\misc> python formats.py −999999999 0
$-999,999,999.00
C:\misc> python formats.py 123456789012345 0
$123,456,789,012,345.00
C:\misc> python formats.py −... |
In some scenarios, you might also
use the built-in `input function introduced in` Chapter 3 and used in Chapter 10 to
prompt the shell user for test inputs instead of pulling them from the command line.
**|**
-----
Also see Chapter 7’s discussion of the new {,d} string format method
syntax that will be available in... |
The module listed here, though, adds money formatting and serves
as a manual alternative for comma insertion for Python versions before
3.1.
###### Changing the Module Search Path
In Chapter 21, we learned that the module search path is a list of directories that can
be customized via the environment variable PYTHONP... |
What
I haven’t shown you until now is how a Python program itself can actually change the
search path by changing a built-in list called sys.path (the path attribute in the builtin sys module). |
sys.path is initialized on startup, but thereafter you can delete, append,
and reset its components however you like:
```
>>> import sys
>>> sys.path
['', 'C:\\users', 'C:\\Windows\\system32\\python30.zip', ...more deleted...]
```
`>>> sys.path.append('C:\\sourcedir')` _# Extend module search path_
`>>> import s... |
In fact, this list may
be changed arbitrarily:
`>>> sys.path = [r'd:\temp']` _# Change module search path_
`>>> sys.path.append('c:\\lp4e\\examples')` _# For this process only_
```
>>> sys.path
['d:\\temp', 'c:\\lp4e\\examples']
>>> import string
Traceback (most recent call last):
File "<stdin>", line 1, in... |
Be careful, though: if you delete a critical directory from the path, you may
lose access to critical utilities. |
In the prior example, for instance, we no longer have
access to the string module because we deleted the Python source library’s directory
from the path.
Also, remember that such sys.path settings endure for only as long as the Python session or program (technically, process) that made them runs; they are not retained... |
PYTHONPATH and .pth file path configurations live in the operating system
instead of a running Python program, and so are more global: they are picked up by
every program on your machine and live on after a program completes.
**|**
-----
###### The as Extension for import and from
Both the import and from statemen... |
The following import statement:
```
import modulename as name
```
is equivalent to:
```
import modulename
name = modulename
del modulename # Don't keep original name
```
After such an import, you can (and in fact must) use the name listed after the as to refer
to the module. |
This works in a from statement, too, to assign a name imported from a
file to a different name in your script:
```
from modulename import attrname as name
```
This extension is commonly used to provide short synonyms for longer names, and to
avoid name clashes when you are already using a name in your script that wo... |
We usually call such manager
programs metaprograms because they work on top of other systems. This is also referred
to as introspection, because programs can see and process object internals. |
Introspection is an advanced feature, but it can be useful for building programming tools.
For instance, to get to an attribute called name in a module called M, we can use qualification or index the module’s attribute dictionary, exposed in the built-in __dict__
attribute we met briefly in Chapter 22. |
Python also exports the list of all loaded modules
as the `sys.modules dictionary (that is, the` `modules attribute of the` `sys module) and`
provides a built-in called getattr that lets us fetch attributes from their string names
(it’s like saying object.attr, but attr is an expression that yields a string at runtime)... |
It defines and exports
a function called listing, which takes a module object as an argument and prints a
formatted listing of the module’s namespace:
```
"""
mydir.py: a module that lists the namespaces of other modules
"""
seplen = 60
sepchr = '-'
def listing(module, verbose=True):
sepline = sepchr * ... |
For instance, the effect
```
of `global X; X=0 can be simulated (albeit with much more typing!) by saying this inside a function:`
```
import sys; glob=sys.modules[__name__]; glob.X=0. |
Remember, each module gets a __name__ attribute for
```
free; it’s visible as a global name inside the functions within the module. |
This trick provides another way to
change both local and global variables of the same name inside a function.
**|**
-----
```
>>> import mydir
>>> help(mydir)
Help on module mydir:
NAME
mydir - mydir.py: a module that lists the namespaces of other modules
FILE
c:\users\veramark\mark\mydir.py
FUN... |
Here’s the sort of output produced in Python 3.0 (to use this in
2.6, enable 3.0 print calls with the __future__ import described in Chapter 11—the
```
end keyword is 3.0-only):
C:\Users\veramark\Mark> c:\Python30\python mydir.py
----------------------------------------------------------- name: mydir file: C:\User... |
Here it is listing attributes in the tkinter GUI module in the standard
library (a.k.a. |
Tkinter in Python 2.6):
```
>>> import mydir
>>> import tkinter
>>> mydir.listing(tkinter)
----------------------------------------------------------- name: tkinter file: c:\PYTHON30\lib\tkinter\__init__.py
----------------------------------------------------------- 00) getdouble <class 'float'>
01) MULTI... |
The point to notice here is that mydir
is a program that lets you browse other programs. |
Because Python exposes its internals,
you can process objects generically.[†]
###### Importing Modules by Name String
The module name in an import or from statement is a hardcoded variable name. |
Sometimes, though, your program will get the name of a module to be imported as a string
at runtime (e.g., if a user selects a module name from within a GUI). |
Unfortunately,
you can’t use import statements directly to load a module given its name as a string—
Python expects a variable name, not a string. |
For instance:
```
>>> import "string"
File "<stdin>", line 1
import "string"
^
SyntaxError: invalid syntax
```
It also won’t work to simply assign the string to a variable name:
```
x = "string"
import x
```
Here, Python will try to import a file x.py, not the string module—the name in an
``... |
The most general approach is to construct an
```
import statement as a string of Python code and pass it to the exec built-in function to
```
run (exec is a statement in Python 2.6, but it can be used exactly as shown here—the
parentheses are simply ignored):
```
>>> modname = "string"
```
`>>> exec("import " + mod... |
Because code in the startup file runs in the interactive
namespace (module __main__), importing common tools in the startup file can save you some typing. |
See
Appendix A for more details.
**|**
-----
The exec function (and its cousin for expressions, eval) compiles a string of code and
passes it to the Python interpreter to be executed. |
In Python, the byte code compiler is
available at runtime, so you can write programs that construct and run other programs
like this. |
By default, exec runs the code in the current scope, but you can get more
specific by passing in optional namespace dictionaries.
The only real drawback to exec is that it must compile the import statement each time
it runs; if it runs many times, your code may run quicker if it uses the built-in
```
__import__ functi... |
The effect is similar, but
__import__ returns the module object, so assign it to a name here to keep it:
>>> modname = "string"
>>> string = __import__(modname)
>>> string
<module 'string' from 'c:\Python30\lib\string.py'>
###### Transitive Module Reloads
```
We studied module reloads in Chapter 22, as a way ... |
When you reload a module, though, Python only
reloads that particular module’s file; it doesn’t automatically reload modules that the
file being reloaded happens to import.
For example, if you reload some module A, and A imports modules B and C, the reload
applies only to A, not to B and C. |
The statements inside A that import B and C are rerun
during the reload, but they just fetch the already loaded B and C module objects (assuming they’ve been imported before). |
In actual code, here’s the file A.py:
```
import B # Not reloaded when A is
import C # Just an import of an already loaded module
% python
>>> . . |
.
>>> from imp import reload
>>> reload(A)
```
By default, this means that you cannot depend on reloads picking up changes in all the
modules in your program transitively—instead, you must use multiple reload calls to
update the subcomponents independently. |
This can require substantial work for large
systems you’re testing interactively. |
You can design your systems to reload their subcomponents automatically by adding reload calls in parent modules like `A, but this`
complicates the modules’ code.
A better approach is to write a general tool to do transitive reloads automatically by
scanning modules’ __dict__ attributes and checking each item’s type t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.