Text stringlengths 1 9.41k |
|---|
How does a module source code file become a module object?
2. Why might you have to set your PYTHONPATH environment variable?
3. Name the four major components of the module import search path.
4. |
Name four file types that Python might load in response to an import operation.
5. |
What is a namespace, and what does a module’s namespace contain?
**|**
-----
###### Test Your Knowledge: Answers
1. |
A module’s source code file automatically becomes a module object when that
module is imported. |
Technically, the module’s source code is run during the
import, one statement at a time, and all the names assigned in the process become
attributes of the module object.
2. |
You only need to set PYTHONPATH to import from directories other than the one in
which you are working (i.e., the current directory when working interactively, or
the directory containing your top-level file).
3. |
The four major components of the module import search path are the top-level
script’s home directory (the directory containing it), all directories listed in the
```
PYTHONPATH environment variable, the standard library directories, and all directo
```
ries listed in .pth path files located in standard places. |
Of these, programmers can
customize PYTHONPATH and .pth files.
4. |
Python might load a source code (.py) file, a byte code (.pyc) file, a C extension
module (e.g., a .so file on Linux or a .dll or .pyd file on Windows), or a directory
of the same name for package imports. |
Imports may also load more exotic things
such as ZIP file components, Java classes under the Jython version of Python, .NET
components under IronPython, and statically linked C extensions that have no files
present at all. |
With import hooks, imports can load anything.
5. A namespace is a self-contained package of variables, which are known as the
_attributes of the namespace object. |
A module’s namespace contains all the names_
assigned by code at the top level of the module file (i.e., not nested in `def or`
```
class statements). |
Technically, a module’s global scope morphs into the module
```
object’s attributes namespace. |
A module’s namespace may also be altered by assignments from other files that import it, though this is frowned upon (see Chapter 17 for more on this issue).
**|**
-----
###### CHAPTER 22
### Module Coding Basics
Now that we’ve looked at the larger ideas behind modules, let’s turn to a simple example of modules in... |
Python modules are easy to _create; they’re just files of_
Python program code created with a text editor. |
You don’t need to write special syntax
to tell Python you’re making a module; almost any text file will do. |
Because Python
handles all the details of finding and loading modules, modules are also easy to use;
clients simply import a module, or specific names a module defines, and use the objects
they reference.
###### Module Creation
To define a module, simply use your text editor to type some Python code into a text
file,... |
All the names assigned at the top level of the module become its
_attributes (names associated with the module object) and are exported for clients to use._
For instance, if you type the following def into a file called module1.py and import it,
you create a module object with one attribute—the name printer, which hap... |
You can call
modules just about anything you like, but module filenames should end in a .py suffix
if you plan to import them. |
The .py is technically optional for top-level files that will
be run but not imported, but adding it in all cases makes your files’ types more obvious
and allows you to import any of your files in the future.
Because module names become variable names inside a Python program (without
the _.py), they should also follow... |
For instance, you can create a module file named if.py, but you cannot import
it because if is a reserved word—when you try to run import if, you’ll get a syntax
error. |
In fact, both the names of module files and the names of directories used in
-----
package imports (discussed in the next chapter) must conform to the rules for variable
names presented in Chapter 11; they may, for instance, contain only letters, digits, and
underscores. |
Package directories also cannot contain platform-specific syntax such as
spaces in their names.
When a module is imported, Python maps the internal module name to an external
filename by adding a directory path from the module search path to the front, and
a .py or other extension at the end. |
For instance, a module named M ultimately maps
to some external file <directory>\M.<extension> that contains the module’s code.
As mentioned in the preceding chapter, it is also possible to create a Python module by
writing code in an external language such as C or C++ (or Java, in the Jython implementation of the lan... |
Such modules are called extension modules, and they are
generally used to wrap up external libraries for use in Python scripts. |
When imported
by Python code, extension modules look and feel the same as modules coded as Python
source code files—they are accessed with import statements, and they provide functions
and objects as module attributes. |
Extension modules are beyond the scope of this book;
see Python’s standard manuals or advanced texts such as Programming Python for more
details.
###### Module Usage
Clients can use the simple module file we just wrote by running an `import or` `from`
statement. |
Both statements find, compile, and run a module file’s code, if it hasn’t yet
been loaded. |
The chief difference is that import fetches the module as a whole, so you
must qualify to fetch its names; in contrast, from fetches (or copies) specific names out
of the module.
Let’s see what this means in terms of code. |
All of the following examples wind up calling
the printer function defined in the prior section’s module1.py module file, but in different ways.
###### The import Statement
In the first example, the name module1 serves two different purposes—it identifies an
external file to be loaded, and it becomes a variable in th... |
Here again, we can
then use the copied name printer in our script without going through the module name:
`>>> from module1 import *` _# Copy out all variables_
```
>>> printer('Hello world!')
Hello world!
```
Technically, both import and from statements invoke the same import operation; the
```
from * form simply... |
It essentially collapses one module’s namespace into another; again,
the net effect is less typing for us.
And that’s it—modules really are simple to use. |
To give you a better understanding of
what really happens when you define and use modules, though, let’s move on to look
at some of their properties in more detail.
In Python 3.0, the from ...* statement form described here can be used
_only at the top level of a module file, not within a function. |
Python 2.6_
allows it to be used within a function, but issues a warning. |
It’s extremely rare to see this statement used inside a function in practice;
when present, it makes it impossible for Python to detect variables statically, before the function runs.
**|**
-----
###### Imports Happen Only Once
One of the most common questions people seem to ask when they start using modules
is, “... |
In fact, they’re not supposed to. This section explains why.
Modules are loaded and run on the first import or from, and only the first. |
This is on
purpose—because importing is an expensive operation, by default Python does it just
once per file, per process. |
Later import operations simply fetch the already loaded
module object.
As one consequence, because top-level code in a module file is usually executed only
once, you can use it to initialize variables. |
Consider the file simple.py, for example:
```
print('hello')
spam = 1 # Initialize variable
```
In this example, the print and = statements run the first time the module is imported,
and the variable spam is initialized at import time:
```
% python
```
`>>> import simple` _# First import: loads and run... |
Thus, the variable spam
is not reinitialized:
`>>> simple.spam = 2` _# Change attribute in module_
`>>> import simple` _# Just fetches already loaded module_
`>>> simple.spam` _# Code wasn't rerun: attribute unchanged_
```
2
```
Of course, sometimes you really want a module’s code to be rerun on a subsequent
import... |
We’ll see how to do this with Python’s reload function later in this chapter.
###### import and from Are Assignments
Just like def, import and from are executable statements, not compile-time declarations.
They may be nested in if tests, appear in function defs, and so on, and they are not
resolved or run until Pytho... |
In other
words, imported modules and names are not available until their associated import or
```
from statements run. |
Also, like def, import and from are implicit assignments:
```
- import assigns an entire module object to a single name.
- from assigns one or more names to objects of the same names in another module.
**|**
-----
All the things we’ve already discussed about assignment apply to module access, too.
For instance,... |
To illustrate, consider the following file, small.py:
```
x = 1
y = [1, 2]
% python
```
`>>> from small import x, y` _# Copy two names out_
`>>> x = 42` _# Changes local x only_
`>>> y[0] = 42` _# Changes shared mutable in-place_
Here, x is not a shared mutable object, but y is. |
The name y in the importer and the
importee reference the same list object, so changing it from one place changes it in the
other:
`>>> import small` _# Get module name (from doesn't)_
`>>> small.x` _# Small's x is not my x_
```
1
```
`>>> small.y` _# But we share a changed mutable_
```
[42, 2]
```
For a graphic... |
Assignment works the same everywhere in
Python.
###### Cross-File Name Changes
Recall from the preceding example that the assignment to x in the interactive session
changed the name x in that scope only, not the x in the file—there is no link from a
name copied with from back to the file it came from. |
To really change a global name in
another file, you must use import:
```
% python
```
`>>> from small import x, y` _# Copy two names out_
`>>> x = 42` _# Changes my x only_
`>>> import small` _# Get module name_
`>>> small.x = 42` _# Changes x in other module_
This phenomenon was introduced in Chapter 17. |
Because changing variables in other
modules like this is a common source of confusion (and often a bad design choice),
we’ll revisit this technique again later in this part of the book. |
Note that the change to
```
y[0] in the prior session is different; it changes an object, not a name.
```
**|**
-----
###### import and from Equivalence
Notice in the prior example that we have to execute an `import statement after the`
```
from to access the small module name at all. |
from only copies names from one module
```
to another; it does not assign the module name itself. |
At least conceptually, a `from`
statement like this one:
```
from module import name1, name2 # Copy these two names out (only)
```
is equivalent to this statement sequence:
```
import module # Fetch the module object
name1 = module.name1 # Copy names out by assignment
name2 = module.name2
... |
Only the names are
copied out, though, not the module itself. |
When we use the from * form of this statement (from module import *), the equivalence is the same, but all the top-level names
in the module are copied over to the importing scope this way.
Notice that the first step of the from runs a normal import operation. |
Because of this,
the from always imports the entire module into memory if it has not yet been imported,
regardless of how many names it copies out of the file. |
There is no way to load just part
of a module file (e.g., just one function), but because modules are byte code in Python
instead of machine code, the performance implications are generally negligible.
###### Potential Pitfalls of the from Statement
Because the from statement makes the location of a variable more imp... |
I’m not sure this advice is warranted,
though; from is commonly and widely used, without too many dire consequences. |
In
practice, in realistic programs, it’s often convenient not to have to type a module’s name
every time you wish to use one of its tools. |
This is especially true for large modules that
provide many attributes—the standard library’s tkinter GUI module, for example.
It is true that the from statement has the potential to corrupt namespaces, at least in
principle—if you use it to import variables that happen to have the same names as
existing variables in ... |
This problem doesn’t occur with the simple `import statement because you must always go`
through a module’s name to get to its contents (module.attr will not clash with a
variable named attr in your scope). |
As long as you understand and expect that this can
happen when using from, though, this isn’t a major concern in practice, especially if
you list the imported names explicitly (e.g., from module import x, y, z).
On the other hand, the from statement has more serious issues when used in conjunction with the reload call... |
In effect, the from * form collapses one namespace into another,
and so defeats the namespace partitioning feature of modules. |
We will explore these
issues in more detail in the section “Module Gotchas” on page 599 at the end of this
part of the book (see Chapter 24).
Probably the best real-world advice here is to generally prefer import to from for simple
modules, to explicitly list the variables you want in most from statements, and to limi... |
That way, any undefined names can be
assumed to live in the module referenced with the from *. |
Some care is required when
using the from statement, but armed with a little knowledge, most programmers find
it to be a convenient way to access modules.
###### When import is required
The only time you really must use import instead of from is when you must use the same
name defined in two different modules. |
For example, if two files define the same name
differently:
_# M.py_
```
def func():
...do something...
```
_# N.py_
```
def func():
...do something else...
```
and you must use both versions of the name in your program, the from statement will
fail—you can only have one assignment to the name in your sc... |
Technically, modules
usually correspond to files, and Python creates a module object to contain all the names
assigned in a module file. |
But in simple terms, modules are just namespaces (places
where names are created), and the names that live in a module are called its attrib_utes. |
We’ll explore how all this works in this section._
###### Files Generate Namespaces
So, how do files morph into namespaces? |
The short story is that every name that is
assigned a value at the top level of a module file (i.e., not nested in a function or class
body) becomes an attribute of that module.
For instance, given an assignment statement such as X = 1 at the top level of a module
file M.py, the name X becomes an attribute of M, which... |
The name X also becomes a global variable to other code inside M.py,
but we need to explain the notion of module loading and scopes a bit more formally
to understand why:
- Module statements run on the first import. |
The first time a module is imported
anywhere in a system, Python creates an empty module object and executes the
statements in the module file one after another, from the top of the file to the
bottom.
- Top-level assignments create module attributes. |
During an import, statements
at the top level of the file not nested in a def or class that assign names (e.g., =,
```
def) create attributes of the module object; assigned names are stored in the mod
```
ule’s namespace.
- Module namespaces can be accessed via the attribute__dict__ **or** `dir(M).`
Module namespac... |
The dir function is roughly equivalent to the sorted
keys list of an object’s __dict__ attribute, but it includes inherited names for classes,
may not be complete, and is prone to changing from release to release.
- Modules are a single scope (local is global). |
As we saw in Chapter 17, names
at the top level of a module follow the same reference/assignment rules as names
in a function, but the local and global scopes are the same (more formally, they
follow the LEGB scope rule we met in Chapter 17, but without the L and E lookup
layers). |
But, in modules, the module scope becomes an attribute dictionary of a
module object after the module has been loaded. |
Unlike with functions (where the
local namespace exists only while the function runs), a module file’s scope becomes
a module object’s attribute namespace and lives on after the import.
**|**
-----
Here’s a demonstration of these ideas. |
Suppose we create the following module file in
a text editor and call it module2.py:
```
print('starting to load...')
import sys
name = 42
def func(): pass
class klass: pass
print('done loading.')
```
The first time this module is imported (or run as a program), Python executes its statements from top to b... |
Some statements create names in the module’s namespace
as a side effect, but others do actual work while the import is going on. |
For instance,
the two print statements in this file execute at import time:
```
>>> import module2
starting to load...
done loading.
```
Once the module is loaded, its scope becomes an attribute namespace in the module
object we get back from import. |
We can then access attributes in this namespace by
qualifying them with the name of the enclosing module:
```
>>> module2.sys
<module 'sys' (built-in)>
>>> module2.name
42
>>> module2.func
<function func at 0x026D3BB8>
>>> module2.klass
<class 'module2.klass'>
```
Here, sys, name, func, and klass were ... |
We’ll talk about classes in Part VI,
but notice the sys attribute—import statements really assign module objects to names,
and any type of assignment to a name at the top level of a file generates a module
attribute.
Internally, module namespaces are stored as dictionary objects. |
These are just normal
dictionary objects with the usual methods. |
We can access a module’s namespace dictionary through the module’s __dict__ attribute (remember to wrap this in a list call
in Python 3.0—it’s a view object):
```
>>> list(module2.__dict__.keys())
['name', '__builtins__', '__file__', '__package__', 'sys', 'klass', 'func',
'__name__', '__doc__']
```
**|**
-----... |
However, Python also adds
some names in the module’s namespace for us; for instance, __file__ gives the name
of the file the module was loaded from, and __name__ gives its name as known to importers (without the .py extension and directory path).
###### Attribute Name Qualification
Now that you’re becoming more famil... |
In Python, you can access the
attributes of any object that has attributes using the qualification syntax
```
object.attribute.
```
Qualification is really an expression that returns the value assigned to an attribute name
associated with an object. |
For example, the expression `module2.sys in the previous`
example fetches the value assigned to sys in module2. |
Similarly, if we have a built-in list
object L, L.append returns the append method object associated with that list.
So, what does attribute qualification do to the scope rules we studied in Chapter 17?
Nothing, really: it’s an independent concept. |
When you use qualification to access
names, you give Python an explicit object from which to fetch the specified names. The
LEGB rule applies only to bare, unqualified names. |
Here are the rules:
_Simple variables_
```
X means search for the name X in the current scopes (following the LEGB rule).
```
_Qualification_
```
X.Y means find X in the current scopes, then search for the attribute Y in the object
X (not in scopes).
```
_Qualification paths_
```
X.Y.Z means look up the name... |
That is, you never automatically get to see names in
another file, regardless of the structure of imports or function calls in your program. |
A
variable’s meaning is always determined by the locations of assignments in your source
code, and attributes are always requested of an object explicitly.
**|**
-----
For example, consider the following two simple modules. |
The first, moda.py, defines
a variable X global to code in its file only, along with a function that changes the global
```
X in this file:
X = 88 # My X: global to this file only
def f():
global X # Change this file's X
X = 99 # Cannot see names in other modules
```
The second ... |
The global scope for`
```
moda.f is always the file enclosing it, regardless of which module it is ultimately called
```
from:
```
% python modb.py
11 99
```
In other words, import operations never give upward visibility to code in imported
files—an imported file cannot see names in the importing file. |
More formally:
- Functions can never see names in other functions, unless they are physically
enclosing.
- Module code can never see names in other modules, unless they are explicitly
imported.
Such behavior is part of the lexical scoping notion—in Python, the scopes surrounding
a piece of code are completely dete... |
Using attribute qualification paths, it’s possible to descend into arbitrarily nested
modules and access their attributes. |
For example, consider the next three files.
_mod3.py defines a single global name and attribute by assignment:_
```
X = 3
```
_mod2.py in turn defines its own X, then imports mod3 and uses qualification to access_
the imported module’s attribute:
- Some languages act differently and provide for dynamic scoping, whe... |
This tends to make code trickier, though, because the meaning of a variable can differ over time.
**|**
-----
```
X = 2
import mod3
print(X, end=' ') # My global X
print(mod3.X) # mod3's X
```
_mod1.py also defines its own X, then imports mod2, and fetches attributes in both the_
first and se... |
By using
the path of names mod2.mod3.X, it can descend into mod3, which is nested in the imported
```
mod2. |
The net effect is that mod1 can see the Xs in all three files, and hence has access to
```
all three global scopes:
```
% python mod1.py
2 3
1 2 3
```
The reverse, however, is not true: mod3 cannot see names in mod2, and mod2 cannot see
names in `mod1. |
This example may be easier to grasp if you don’t think in terms of`
namespaces and scopes, but instead focus on the objects involved. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.