Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions

  




 

 

Module Use: The import Statement

Since a module is just a Python file, there are two ways to use a module. We can import the module, to make use of it's definitions, or we can execute it as a script file to have it do useful work. We started looking at execution of scripts back in the section called “Script Mode”, and have been using it heavily.

We looked briefly at the import statement in the section called “Using Modules”. There are several variations on this statement that we'll look at in the next section. In this section, we'll look at more features of the import statement.

The essential import statement has the following syntax:

import module

The module name is the Python file name with the ".py" file extension removed.

Python does the following.

  1. Search the global namespace for the module. If the module exists, it had already been imported; for the basic import , nothing more needs to be done.

  2. If the module doesn't exist, search the Python path for a file; the file name is the module name plus the ".py" extension. The search path has a default value, and can be modified by command-line arguments and by environment variables. If the module name can't be found anywhere on the path, an ImportError exception is raised.

  3. If the file was found, create the module's new, unique namespace; this is the container in which the module's definitions and module-level variables will be created. Execute the statements in the module, using the module's namespace to store the variables and definitions. We'll look close at namespaces below.

The most important effect of importing a module is that the Python definitions from the module are now part of the running Python environment. Each class, function or variable defined in the module is available for use. Since these objects are contained in the module's namespace, The names of those elements must be qualified by the module's name.

In the following example, we import the dice module. Python will search for module dice, then for the file dice.py from which to create the module. After importing, create an instance of the Dice class and called that instance craps. We qualified the class name with the module name: dice.Dice.

>>> import dice
>>> craps= dice.Dice()
>>> craps.roll()
>>> craps.dice()
(3, 5)

Namespaces. Python maintains a number of local namespaces and one global namespace. A unique local namespace is used when evaluating each function or method function. In effect, a variable created in a function's namespace is private to that function; it only exists while the function executes.

Typically, when a module is imported, the module's namespace is the only thing created in the global namespace. All of the module's objects are inside the module's namespace.

You can explore this by using the built-in dir function. Do the following sequence of steps.

  1. Create a small module file (like the dice.py example, above).

  2. Start a fresh command-line Python interpreter in the same directory as your module file. Starting the intepreter in the same directory is the simplest way to be sure that your module will be found by the import statement.

  3. Evalute the dir function to see what is in the initial global namespace.

  4. Import your module.

  5. Evaluate the dir function to see what got added to the namespace.

Scripts and Modules. There are two ways to use a Python file. We can execute it as a script or we can import it as a library module. We need to keep this distinction clear when we create our Python applications. The file that a user executes will do useful work, and must be a script of some kind. This script can be an icon that the user double-clicked, or a command that the user typed at a command prompt; in either case, a single Python script initiates the processing.

A file that is imported will provide definitions. We'll emphasize this distinction.

Bad Behavior

The standard expectation is that a library module will contain only definitions. Some modules create module global variables; this must be fully documented. It is bad behavior for an imported module to attempt to do any real work beyond creating definitions. Any real work that a library module does makes reuse of that module nearly impossible.

Importing a module means the module file is executed. This creates is an inherent, but important ambiguity. A given file can be used as a script or used as a library; any file can be used either way. Here's the complete set of alternatives.

A top-level script.

You execute a script with the Run Module menu item in IDLE. You can also execute a script from your operating system command prompt. For example, python file .py will execute the given file as a script. Also, you can set up most operating systems so that entering file.py at the command prompt will execute the file as a script. Also, you can set up most GUI's so that double-clicking the file.py icon will launch Python and execute the given file as a script.

import

You can import a library module. As described above, Python will not import a module more than once. If the module was not previously imported, Python creates a namespace and executes the file. The namespace is saved.

exec

Python's exec statement is similar to the import statement, with an important difference: The exec statement executes a file in the current namespace. The exec statement doesn't create a new namespace. We'll look at this in the section called “The exec Statement”.

The Main-Import Switch. Since a file can be used as script or library, we can intentionally create files that are both. We can create a script which can also be used as a library. And we can create a library which has a useful behavior when used as a script. This promotes reuse of libraries.

Python provides a global variable that helps to differentiate between a main program script and a module library module. The global __name__ variable is equal to "__main__" when the initial (or “top-level” or “outermost”) file is being processed. For example, when you have an executable script, and you run that script from the command line, that script sees __name__ equal to "__main__". However, when an import is in process, the __name__ variable is the name of the module being imported.

As an example, we can make use of this to provide stand-alone unit testing for a library module. When we write a module that is primarily definitional, we can have it execute it's own unit tests when it is used as a main program. This makes testing a library module simple: we import it and it runs its unit test. We do this by examining the __name__ variable.

if __name__ == "__main__":
    unittest.main()

When some other script imports a module (for example, named dice.py), the __name__ variable is "dice" and nothing special is done. When testing, however, we can execute the module by itself; in this case the __name__ variable is "__main__" and the test function is executed.


 
 
  Published under the terms of the Open Publication License Design by Interspire