Text stringlengths 1 9.41k |
|---|
In
fact, you won’t even need to configure the module search path to use these programs
on your computer—because Python always searches the home directory first (that is,
the directory containing the top-level file), imports in either system’s files will automatically see all the files in that system’s directory. |
For instance, if you click on
_system1\main.py, all imports will search_ _system1 first. Similarly, if you launch_
**|**
-----
_system2\main.py, system2 will be searched first instead. |
Remember, module search path_
settings are only needed to import across directory boundaries.
However, suppose that after you’ve installed these two programs on your machine, you
decide that you’d like to use some of the code in each of the utilities.py files in a system
of your own. |
It’s common utility code, after all, and Python code by nature wants to
be reused. |
In this case, you want to be able to say the following from code that you’re
writing in a third directory to load one of the two files:
```
import utilities
utilities.func('spam')
```
Now the problem starts to materialize. |
To make this work at all, you’ll have to set the
module search path to include the directories containing the utilities.py files. |
But which
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 to
right, so no matter how long you ponder this dilemma, you will always get utilities.py
from the directory listed first (leftmost) on the search path. |
As is, you’ll never be able
to import it from the other directory at all. |
You could try changing sys.path within
your script before each import operation, but that’s both extra work and highly error
prone. |
By default, you’re stuck.
This is the issue that packages actually fix. |
Rather than installing programs as flat lists
of files in standalone directories, you can package and install them as subdirectories
under a common root. |
For instance, you might organize all the code in this example as
an install hierarchy that looks like this:
```
root\
system1\
__init__.py
utilities.py
main.py
other.py
system2\
__init__.py
utilities.py
main.py
other.py
system3\ # Here or elsewhere
... |
If your code’s imports
are all relative to this common root, you can import either system’s utility file with a
package import—the enclosing directory name makes the path (and hence, the module
reference) unique. |
In fact, you can import both utility files in the same module, as long
as you use an import statement and repeat the full path each time you reference the
utility modules:
**|**
-----
```
import system1.utilities
import system2.utilities
system1.utilities.function('spam')
system2.utilities.function('eggs')
... |
If the name of the called function here
was different in each path, from statements could be used to avoid repeating the full
package path whenever you call one of the functions, as described earlier.
Also, notice in the install hierarchy shown earlier that __init__.py files were added to
the system1 and system2 direc... |
However, because you never know when
your own modules might be useful in other programs, you might as well place them
under the common root directory as well to avoid similar name-collision problems in
the future.
Finally, notice that both of the two original systems’ imports will keep working unchanged. |
Because their home directories are searched first, the addition of the common
root on the search path is irrelevant to code in system1 and system2; they can keep
saying just import utilities and expect to find their own files. |
Moreover, if you’re
careful to unpack all your Python systems under a common root like this, path configuration becomes simple: you’ll only need to add the common root directory, once.
###### Package Relative Imports
The coverage of package imports so far has focused mostly on importing package files
from outside the... |
Within the package itself, imports of package files can use
the same path syntax as outside imports, but they can also make use of special intrapackage search rules to simplify import statements. |
That is, rather than listing package
import paths, imports within the package can be relative to the package.
The way this works is version-dependent today: Python 2.6 implicitly searches package
directories first on imports, while 3.0 requires explicit relative import syntax. |
This 3.0
change can enhance code readability, by making same-package imports more obvious.
If you’re starting out in Python with version 3.0, your focus in this section will likely
be on its new import syntax. |
If you’ve used other Python packages in the past, though,
you’ll probably also be interested in how the 3.0 model differs.
**|**
-----
###### Changes in Python 3.0
The way import operations in packages work has changed slightly in Python 3.0. |
This
change applies only to imports within files located in the package directories we’ve
been studying in this chapter; imports in other files work as before. |
For imports in
packages, though, Python 3.0 introduces two changes:
- It modifies the module import search path semantics to skip the package’s own
directory by default. |
Imports check only other components of the search path.
These are known as “absolute” imports.
- It extends the syntax of from statements to allow them to explicitly request that
imports search the package’s directory only. |
This is known as “relative” import
syntax.
These changes are fully present in Python 3.0. |
The new from statement relative syntax
is also available in Python 2.6, but the default search path change must be enabled as
an option. |
It’s currently scheduled to be added in the 2.7 release[†]—this change is being
phased in this way because the search path portion is not backward compatible with
earlier Pythons.
The impact of this change is that in 3.0 (and optionally in 2.6), you must generally use
special from syntax to import modules located in t... |
Without this syntax, your
package is not automatically searched.
###### Relative Import Basics
In Python 3.0 and 2.6, from statements can now use leading dots (“.”) to specify that
they require modules located within the same package (known as package relative im_ports), instead of modules located elsewhere on the mo... |
That is:_
- In both Python 3.0 and 2.6, you can use leading dots in from statements to indicate
that imports should be _relative to the containing package—such imports will_
search for modules inside the package only and will not look for same-named
modules located elsewhere on the import search path (sys.path). |
The net effect is
that package modules override outside modules.
- In Python 2.6, normal imports in a package’s code (without leading dots) currently
default to a relative-then-absolute search path order—that is, they search the package’s own directory first. |
However, in Python 3.0, imports within a package are
absolute by default—in the absence of any special dot syntax, imports skip the
containing package itself and look elsewhere on the sys.path search path.
† Yes, there will be a 2.7 release, and possibly 2.8 and later releases, in parallel with new releases in the 3.X... |
As described in the Preface, both the Python 2 and Python 3 lines are expected to be fully supported for
years to come, to accommodate the large existing Python 2 user and code bases.
**|**
-----
For example, in both Python 3.0 and 2.6, a statement of the form:
```
from . |
import spam # Relative to this package
```
instructs Python to import a module named spam located in the same package directory
as the file in which this statement appears. |
Similarly, this statement:
```
from .spam import name
```
means “from a module named spam located in the same package as the file that contains
this statement, import the variable name.”
The behavior of a statement _without the leading dot depends on which version of_
Python you use. |
In 2.6, such an import will still default to the current
relative-then-absolute search path order (i.e., searching the package’s directory first),
unless a statement of the following form is included in the importing file:
```
from __future__ import absolute_import # Required until 2.7?
```
If present, this stateme... |
For instance, in 3.0’s model, a statement of the following form
will always find a string module somewhere on sys.path, instead of a module of the
same name in the package:
```
import string # Skip this package's version
```
Without the from __future__ statement in 2.6, if there’s a string module in th... |
To get the same behavior in 3.0 and in 2.6 when the absolute
import change is enabled, run a statement of the following form to force a relative
import:
```
from . |
import string # Searches this package only
```
This works in both Python 2.6 and 3.0 today. |
The only difference in the 3.0 model is
that it is required in order to load a module that is located in the same package directory
as the file in which this appears, when the module is given with a simple name.
Note that leading dots can be used to force relative imports only with the from statement, not with the imp... |
In Python 3.0, the import modname statement is
always absolute, skipping the containing package’s directory. |
In 2.6, this statement
form still performs relative imports today (i.e., the package’s directory is searched first),
but these will become absolute in Python 2.7, too. |
from statements without leading dots
behave the same as import statements—absolute in 3.0 (skipping the package directory), and relative-then-absolute in 2.6 (searching the package directory first).
Other dot-based relative reference patterns are possible, too. |
Within a module file located in a package directory named mypkg, the following alternative import forms work
as described:
**|**
-----
```
from .string import name1, name2 # Imports names from mypkg.string
from . |
import string # Imports mypkg.string
from .. |
import string # Imports string sibling of mypkg
```
To understand these latter forms better, we need to understand the rationale behind
this change.
###### Why Relative Imports?
This feature is designed to allow scripts to resolve ambiguities that can arise when a
same-named file appears in multiple place... |
Consider the
following package directory:
```
mypkg\
__init__.py
main.py
string.py
```
This defines a package named `mypkg containing modules named` `mypkg.main and`
```
mypkg.string. |
Now, suppose that the main module tries to import a module named
string. In Python 2.6 and earlier, Python will first look in the mypkg directory to per
```
form a relative import. |
It will find and import the string.py file located there, assigning
it to the name string in the mypkg.main module’s namespace.
It could be, though, that the intent of this import was to load the Python standard
library’s string module instead. |
Unfortunately, in these versions of Python, there’s no
straightforward way to ignore mypkg.string and look for the standard library’s string
module located on the module search path. |
Moreover, we cannot resolve this with
package import paths, because we cannot depend on any extra package directory
structure above the standard library being present on every machine.
In other words, imports in packages can be ambiguous—within a package, it’s not clear
whether an import spam statement refers to a mod... |
But this doesn’t help if a package accidentally hides a standard module; moreover, Python might add a new standard library module in the future that has
the same name as a module of your own. |
Code that relies on relative imports is also
less easy to understand, because the reader may be confused about which module is
intended to be used. |
It’s better if the resolution can be made explicit in code.
###### The relative imports solution in 3.0
To address this dilemma, imports run within packages have changed in Python 3.0
(and as an option in 2.6) to be absolute. |
Under this model, an import statement of the
**|**
-----
following form in our example file mypkg/main.py will always find a string outside the
package, via an absolute import search of sys.path:
```
import string # Imports string outside package
```
A from import without leading-dot syntax is consid... |
import string # Imports mypkg.string (relative)
```
This form imports the string module relative to the current package only and is the
relative equivalent to the prior import example’s absolute form; when this special relative syntax is used, the package’s directory is the only directory searched.
We can al... |
If this
code appears in our mypkg.main module, for example, it will import name1 and name2
from mypkg.string.
In effect, the “.” in a relative import is taken to stand for the package directory con_taining the file in which the import appears. |
An additional leading dot performs the_
relative import starting from the _parent of the current package. For example, this_
statement:
```
from .. |
import spam # Imports a sibling of mypkg
```
will load a sibling of mypkg—i.e., the spam module located in the package’s own container directory, next to mypkg. |
More generally, code located in some module A.B.C can
do any of these:
```
from . import D # Imports A.B.D (. means A.B)
from .. import E # Imports A.E (.. |
means A)
from .D import X # Imports A.B.D.X (. means A.B)
from ..E import X # Imports A.E.X (.. |
means A)
###### Relative imports versus absolute package paths
```
Alternatively, a file can sometimes name its own package explicitly in an absolute import statement. |
For example, in the following, mypkg will be found in an absolute directory on sys.path:
```
from mypkg import string # Imports mypkg.string (absolute)
```
However, this relies on both the configuration and the order of the module search path
settings, while relative import dot syntax does not. |
In fact, this form requires that the
directory immediately containing `mypkg be included in the module search path. |
In`
**|**
-----
general, absolute import statements must list all the directories below the package’s
root entry in sys.path when naming packages explicitly like this:
```
from system.section.mypkg import string # system container on sys.path only
```
In large or deep packages, that could be much more work tha... |
import string # Relative import syntax
```
With this latter form, the containing package is searched automatically, regardless of
the search path settings.
###### The Scope of Relative Imports
Relative imports can seem a bit perplexing on first encounter, but it helps if you remember a few key points abou... |
Keep in mind that
this feature’s module search path change applies only to import statements within
module files located in a package. |
Normal imports coded outside package files still
work exactly as described earlier, automatically searching the directory containing
the top-level script first.
- Relative imports apply to the from statement only. |
Also remember that this
feature’s new syntax applies only to from statements, not import statements. It’s
detected by the fact that the module name in a from begins with one or more dots
(periods). |
Module names that contain dots but don’t have a leading dot are package
imports, not relative imports.
- The terminology is ambiguous. |
Frankly, the terminology used to describe this
feature is probably more confusing than it needs to be. Really, all imports are relative to something. |
Outside a package, imports are still relative to directories listed
on the sys.path module search path. |
As we learned in Chapter 21, this path includes the program’s container directory, PYTHONPATH settings, path file settings,
and standard libraries. |
When working interactively, the program container directory is simply the current working directory.
For imports made inside packages, 2.6 augments this behavior by searching the
package itself first. |
In the 3.0 model, all that really changes is that normal “absolute” import syntax skips the package directory, but special “relative” import syntax causes it to be searched first and only. |
When we talk about 3.0 imports as being
“absolute,” what we really mean is that they are relative to the directories on
```
sys.path, but not the package itself. |
Conversely, when we speak of “relative” im
```
ports, we mean they are relative to the package directory only. Some `sys.path`
entries could, of course, be absolute or relative paths too. |
(And I could probably
make up something more confusing, but it would be a stretch!)
**|**
-----
In other words, “package relative imports” in 3.0 really just boil down to a removal of
2.6’s special search path behavior for packages, along with the addition of special
```
from syntax to explicitly request relative b... |
If you wrote your package imports
```
in the past to not depend on 2.6’s special implicit relative lookup (e.g., by always spelling out full paths from a package root), this change is largely a moot point. |
If you didn’t,
you’ll need to update your package files to use the new from syntax for local package
files.
###### Module Lookup Rules Summary
With packages and relative imports, the module search story in Python 3.0 in its entirety
can be summarized as follows:
- Simple module names (e.g., A) are looked up by sear... |
This list is constructed from both system defaults
```
and user-configurable settings.
- Packages are simply directories of Python modules with a special __init__.py file,
which enables A.B.C directory path syntax in imports. |
In an import of A.B.C, for
example, the directory named A is located relative to the normal module import
search of sys.path, B is another package subdirectory within A, and C is a module
or other importable item within B.
- Within a package’s files, normal import statements use the same sys.path search
rule as impor... |
Imports in packages using from statements and leading
dots, however, are relative to the package; that is, only the package directory is
checked, and the normal `sys.path lookup is not used. |
In` `from . |
import A, for`
example, the module search is restricted to the directory containing the file in which
this statement appears.
###### Relative Imports in Action
But enough theory: let’s run some quick tests to demonstrate the concepts behind
relative imports.
###### Imports outside packages
First of all, as mentione... |
Thus, the following finds the standard library string module as expected:
```
C:\test> c:\Python30\python
>>> import string
>>> string
<module 'string' from 'c:\Python30\lib\string.py'>
```
**|**
-----
But if we add a module of the same name in the directory we’re working in, it is selected
instead, because... |
In fact, relative import syntax is
not even allowed in code that is not in a file being used as part of a package:
```
>>> from . |
import string
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Attempted relative import in non-package
```
In this and all examples in this section, code entered at the interactive prompt behaves
the same as it would if run in a top-level script, because the first entry on sys... |
That
is, 2.6 searches the containing package first, but 3.0 does not. |
This is the noncompatible
behavior you have to be aware of in 3.0:
```
C:\test> c:\Python26\python
>>> import pkg.spam
<module 'string' from 'c:\Python26\lib\string.pyc'>
99999
C:\test> c:\Python30\python
>>> import pkg.spam
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File... |
import eggs # <== Use package relative import in 2.6 or 3.0
print(eggs.X)
```
_# test\pkg\eggs.py_
```
X = 99999
import string
print(string)
C:\test> c:\Python26\python
>>> import pkg.spam
<module 'string' from 'c:\Python26\lib\string.pyc'>
99999
C:\test> c:\Python30\python
>>> import pkg.spa... |
Really, their imports are still relative to the entries on the
module search path, even if those entries are relative themselves. |
If you add a string
module to the CWD again, imports in a package will find it there instead of in the
standard library. |
Although you can skip the package directory with an absolute import
in 3.0, you still can’t skip the home directory of the program that imports the package:
_# test\string.py_
```
print('string' * 8)
```
_# test\pkg\spam.py_
```
from . |
import eggs
```
**|**
-----
```
print(eggs.X)
```
_# test\pkg\eggs.py_
```
X = 99999
import string # <== Gets string in CWD, not Python lib!
print(string)
```
`C:\test> c:\Python30\python` _# Same result in 2.6_
```
>>> import pkg.spam
stringstringstringstringstringstringstringstring
<module... |
Get rid of the local string module, and define a new one inside the
package itself:
```
C:\test> del string*
```
_# test\pkg\spam.py_
```
import string # <== Relative in 2.6, absolute in 3.0
print(string)
```
_# test\pkg\string.py_
```
print('Ni' * 8)
```
Now, which version of the string module you g... |
In fact, this is the use case that the 3.0 model addresses:
_# test\pkg\spam.py_
```
from . |
import string # <== Relative in both 2.6 and 3.0
print(string)
```
_# test\pkg\string.py_
```
print('Ni' * 8)
C:\test> c:\Python30\python
>>> import pkg.spam
NiNiNiNiNiNiNiNi
```
**|**
-----
```
<module 'pkg.string' from 'pkg\string.py'>
C:\test> c:\Python26\python
>>> import pkg.spam
NiNiNi... |
If we delete the string.py file in this example, the relative import in
_spam.py_ _fails in both 3.0 and 2.6, instead of falling back on the standard library’s version_
of this module (or any other):
_# test\pkg\spam.py_
```
from . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.