Module Structure and Layout

Một phần của tài liệu Core python programming 2nd edition sep 2006 (Trang 108 - 111)

Modules are simply physical ways of logically organizing all your Python code.

Within each file, you should set up a consistent and easy-to-read structure.

One such layout is the following:

# (1) startup line (Unix)

# (2) module documentation

# (3) module imports

# (4) variable declarations

# (5) class declarations

# (6) function declarations

# (7) "main" body

Figure 3–1 illustrates the internal structure of a typical module.

(1) Startup line

Generally used only in Unix environments, the startup line allows for script execution by name only (invoking the interpreter is not required).

(2) Module documentation

Summary of a module’s functionality and significant global vari- ables; accessible externally as module.__doc__.

ptg 72 Chapter 3 Python Basics

(3) Module imports

Import all the modules necessary for all the code in current module; modules are imported once (when this module is loaded); imports within functions are not invoked until those functions are called.

(4) Variable declarations

Declare here (global) variables that are used by multiple func- tions in this module. We favor the use of local variables over globals, for good programming style mostly, and to a lesser extent, for improved performance and less memory usage.

(5) Class declarations

Any classes should be declared here. A class is defined when this module is imported and the class statement executed.

Documentation variable is class.__doc__.

Figure 3–1 Typical Python file structure

#/usr/bin/env python (1) Startup line (Unix)

"this is a test module" (2) Module documentation

import sys

import os (3) Module imports

debug = True (4) (Global) Variable declarations

class FooClass (object):

"Foo class"

pass

(5) Class declarations (if any)

def test():

"test function"

foo = FooClass() if debug:

print 'ran test()'

(6) Function declarations (if any)

if ——name—— == '——main——':

test() (7) “main” body

ptg 3.4 Basic Style Guidelines 73

(6) Function declarations

Functions that are declared here are accessible externally as module.function(); function is defined when this module is imported and the def statement executed. Documentation variable is function.__doc__.

(7) “main” body

All code at this level is executed, whether this module is imported or started as a script; generally does not include much functional code, but rather gives direction depending on mode of execution.

CORE STYLE: “main” calls main()

The main body of code tends to contain lines such as the ones you see above, which check the __name__ variable and take appropriate action (see Core Note on the following page). Code in the main body typically executes the class, function, and variable declarations, then checks __name__

to see whether it should invoke another function (often called main()), which performs the primary duties of this module. The main body usually does no more than that. (Our example above uses test() rather than main() to avoid confusion until you read this Core Style sidebar.)

Regardless of the name, we want to emphasize that this is a great place to put a test suite in your code. As we explain in Section 3.4.2, most Python modules are created for import use only, and calling such a module directly should invoke a regression test of the code in such a module.

Most projects tend to consist of a single application and import any required modules. Thus it is important to bear in mind that most modules are created solely to be imported rather than to execute as scripts. We are more likely to create a Python library-style module whose sole purpose is to be imported by another module. After all, only one of the modules—the one that houses the main application—will be executed, either by a user from the command line, by a batch or timed mechanism such as a Unix cron job, via a Web server call, or through a GUI callback.

With that fact in hand, we should also remember that all modules have the ability to execute code. All Python statements in the highest level of code—

that is, the lines that are not indented—will be executed on import, whether desired or not. Because of this “feature,” safer code is written such that everything is in a function except for the code that should be executed on an import of a module. Again, usually only the main application module has the bulk of the executable code at its highest level. All other imported modules

ptg 74 Chapter 3 Python Basics

will have very little on the outside, and everything in functions or classes.

(See Core Note that follows for more information.)

CORE NOTE: __name__ indicates how module was loaded

Because the “main” code is executed whether a module is imported or executed directly, we often need to know how this module was loaded to guide the execution path. An application may wish to import the module of another application, perhaps to access useful code which will otherwise have to be duplicated (not the OO thing to do). However, in this case, you only want access to this other application’s code, not necessarily to run it.

So the big question is, “Is there a way for Python to detect at runtime whether this module was imported or executed directly?” The answer is . . . (drum roll . . . ) yes! The __name__ system variable is the ticket.

__name__ contains module name if imported

__name__ contains ’__main__’ if executed directly

Một phần của tài liệu Core python programming 2nd edition sep 2006 (Trang 108 - 111)

Tải bản đầy đủ (PDF)

(1.137 trang)