I l@ve RuBoard Previous Section Next Section

1.3 A First Look at Module Files

Earlier in this chapter, we saw how to run module files (i.e., text files containing Python statements) from the operating-system shell's command line. It turns out that we can also run module files from Python's interactive command line by importing or reloading them, as we'd normally do from other system components. The details of this process are covered in Chapter 5, but since this turns out to be a convenient way to save and run examples, we'll give a quick introduction to the process.

The basic idea behind importing modules is that importers may gain access to names assigned at the top level of a module file. The names are usually assigned to services exported by the modules. For instance, suppose we use our favorite text editor to create the one-line Python module file myfile.py, shown in the following code snippet. This may be one of the world's simplest Python modules, but it's enough to illustrate basic module use:

title = "The Meaning of Life"

Notice that the filename has a .py suffix: this naming convention is required for files imported from other components. Now we can access this module's variable title in other components two different ways, either by importing the module as a whole with an import statement and qualifying the module by the variable name we want to access:

% python                        ?/b>燬tart Python
>>> import myfile               ?/b>燫un file, load module as a whole
>>> print myfile.title          ?/b>燯se its names: '.' qualification
The Meaning of Life

or by fetching (really, copying) names out of a module with from statements:

% python                        ?/B>燬tart Python
>>>?/b> from myfile import title?/b>    燫un file, load its names
>>> print title                 ?/b>燯se name directly: no need to qualify
The Meaning of Life

As we'll see later, from is much like an import, with an extra assignment to names in the importing component. Notice that both statements list the name of the module file as simply myfile, without its .py suffix; when Python looks for the actual file, it knows to include the suffix.

Whether we use import or from, the statements in the module file myfile.py are executed, and the importing component (here, the interactive prompt) gains access to names assigned at the top level of the file. There's only one such name in this simple example梩he variable title, assigned to a string梑ut the concept will be more useful when we start defining objects such as functions and classes. Such objects become services accessed by name from one or more client modules.

When a module file is imported the first time in a session, Python executes all the code inside it, from the top to the bottom of the file. Because of this, importing a module interactively is another way to execute its code all at once (instead of, for instance, running it from the system shell with a command such as python myfile.py). But there's one catch to this process: Python executes a module file's code only the first time it's imported. If you import it again during the same interactive session, Python won't reexecute the file's code, even if you've changed it with your editor. To really rerun a file's code without stopping and restarting the interactive interpreter, you can use the Python reload function, as follows:

% python                        ?/b>燬tart Python
>>> import myfile               ?/B>燫un/load module
>>> print myfile.title          ?/b>燪ualify to fetch name
The Meaning of Life

燙hange myfile.py in your text editor

>>> import myfile               ?/b>燱ill NOT rerun the file's code

>>> reload(myfile)              ?/b>燱ILL rerun the file's (current) code

While this scheme works, reload has a few complications, and we suggest you avoid it for now (just exit and reenter the interpreter between file changes). On the other hand, this has proven to be a popular testing technique in Python classes, so you be the judge.

1.3.1 A First Look at Namespace Inspection

Another trick that has proven popular is using the dir built-in function to keep track of defined names while programming interactively. We'll have more to say about it later, but before we turn you loose to work on some exercises, here is a brief introduction. If you call the dir function without arguments, you get back a Python list (described in Chapter 2) containing all the names defined in the interactive namespace:

>>> x = 1
>>> y = "shrubbery"
>>> dir()
['__builtins__', '__doc__', '__name__', 'x', 'y']

Here, the expression dir() is a function call; it asks Python to run the function named dir. We'll meet functions in Chapter 4; but for now, keep in mind that you need to add parenthesis after a function name to call it (whether it takes any arguments or not).

When dir is called, some of the names it returns are names you get "for free": they are built-in names that are always predefined by Python. For instance, _ _name__ is the module's filename, and _ _builtins__ is a module containing all the built-in names in Python (including dir). Other names are variables that you've assigned values to (here, x and y). If you call dir with a module as an argument, you get back the names defined inside that module:[5]

[5] Technically, in the module's namespace梐 term we'll soon use so often that you'll probably get tired of hearing it. Since we're being technical anyhow, the interactive command line is really a module too, called __main__; code you enter there works as if it were put in a module file, except that expression results are printed back to you. Notice that the result of a dir call is a list, which could be processed by a Python program. For now, hold that thought: namespaces can be fetched in other ways too.

% cat threenames.py?/b>
a = 'dead'
b = 'parrot'
c = 'sketch'
% python?/b>
>>> import threenames?/B>
>>> dir(threenames?/B>)
['__builtins__', '__doc__', '__file__', '__name__', 'a', 'b', 'c']
>>> dir(?/b>__builtins?/b>__)?/B>
燗ll the names Python predefines for you

Later, we'll see that some objects have additional ways of telling clients which names they expose (e.g., special attributes such as __methods__ and _ _members__). But for now, the dir function lets you do as much poking around as you'll probably care to do.

I l@ve RuBoard Previous Section Next Section