Section 2.19. Modules


2.19. Modules

A module is a logical way to physically organize and distinguish related pieces of Python code into individual files. A module can contain executable code, functions, classes, or any and all of the above.

When you create a Python source file, the name of the module is the same as the file except without the trailing .py extension. Once a module is created, you may import that module for use from another module using the import statement.

How to Import a Module

  import module_name


How to Call a Module Function or Access a Module Variable

Once imported, a module's attributes (functions and variables) can be accessed using the familiar dotted attribute notation:

  module.function()   module.variable


We will now present our Hello World! example again, but using the output functions inside the sys module.

  >>> import sys   >>> sys.stdout.write('Hello World!\n')   Hello World!   >>> sys.platform   'win32'   >>> sys.version   '2.4.2 (#67, Sep 28 2005, 10:51:12) [MSC v.1310 32 bit   (Intel)]'


This code behaves just like our original Hello World! using the print statement. The only difference is that the standard output write() method is called, and the NEWLINE character needs to be stated explicitly because, unlike the print statement, write() does not do that for you.

You can find out more information on modules and importing in Chapter 12.

We will cover all of the above topics in much greater detail throughout the text, but hopefully we have provided enough of a "quick dip in the pool" to facilitate your needs if your primary goal is to get started working with Python as quickly as possible without too much serious reading.

Core Note: What is a "PEP"?

You will find references throughout the book to PEP. A PEP is a Python Enhancement Proposal, and this is the way new features are introduced to future versions of Python. They are usually advanced reading from the beginner's point of view, but they provide a full description of a new feature, the rationale or motivation behind it, a new syntax if that is necessary, technical implementation details, backwards-compatibility information, etc. Agreement has to be made between the Python development community, the PEP authors and implementors, and finally, the creator of Python itself, Guido van Rossum, adoringly referred to as the BDFL (Benevolent Dictator for Life), before any new feature is integrated. PEP 1 introduces the PEP, its purpose and guidelines. You can find all of the PEPs in PEP 0, the PEP index, at: http://python.org/dev/peps.




Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

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