1.3 A First Look at Module Files

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   Start Python  
 >>>  import myfile   Run file, load module as a whole  
 >>>  print myfile.title   Use its names: '.' qualification  
 The Meaning of Life 

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

 %  python   Start Python  
  >>>   from myfile import title   Run file, load its names  
 >>>  print title   Use 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 examplethe variable title , assigned to a stringbut 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   Start Python  >>>  import myfile   Run/load module  >>>  print myfile.title   Qualify to fetch name  The Meaning of Life  Change myfile.py in your text editor  >>>  import myfile   Will NOT rerun the file's code  >>>  reload(myfile)   WILL 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 a 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  a = 'dead' b = 'parrot' c = 'sketch' %  python  >>>  import threenames  >>>  dir(threenames  ) ['__builtins__', '__doc__', '__file__', '__name__', 'a', 'b', 'c'] >>>  dir(  __  builtins  __  )   All 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.



Learning Python
Learning Python: Powerful Object-Oriented Programming
ISBN: 0596158068
EAN: 2147483647
Year: 1999
Pages: 156
Authors: Mark Lutz

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net