The Tutorial:

    Lesson 5: Python Modules

    Now that we have learned how to manage data, control flow, and functions, we can look at more advanced high-level methods of constructing programs: modules.  Modules are program files that clients can import into their own code for use.  Whether it is a module designed by the creator of Python or one you create yourself, modules facilitate code reuse, namespace partitioning, and code sharing.  In large-scale projects with many programmers, the ability to develop code in modules as blocks that can be share between one another is paramount [ 4, 2: 127].

    Let's look at a simple module: 

    # Module attribute that just prints.
    def simple_print(thing):
    print thing

    By saving the above file as we have created our first module.  In order to gain access to the code saved in, we have to use the built-in function import at the top of our program.  Once we import the module into our code, we must use the '.' qualifier to access simple_print.  This qualifier tells the interpreter where to look for the attribute simple_print. Example Code 5.1 uses the import funtion to get the module_5 module, and runs the function simple_print.

    Code Example 5.1: 

    # Print the required header that tells the browser how to render the text.
    print "Content-Type: text/plain\n\n"

    # Import the outside module.
    import module_5

    # Call the 'simple_print' function using a qualifier.
    module_5.simple_print("This is printing made hard.")

    Notice that the '.' qualifier tells the interpreter in module_5.simple_print("This is printing made hard.") to search for simple_print in module module_5 and send to it the parameter "This is printing made hard.".

    Note to C++ and Java Programmers

    Programmers used to information hiding and encapsulation should be warned that Python does not separate those variables that should and should not be visible outside the module.  In short, Python does not provide a "private" or "protected" mechanism.  Information hiding in Python is a programming convention and is not enforced by the language itself [2: 137].

    To Lesson 6 ...

 © 2000 Department of Computer Science, University of Virginia