Originally Published: Wednesday, 25 July 2001 Author: Ken McDonald and Darryl Harms
Published to: develop_articles/Development Articles Page: 1/4 - [Printable]

Chapter 11, The Quick Python Book: Modules and Scoping rules

Linux.com is proud to feature the following article on Python modules and scooping from the book "The Quick Python Book", published by Manning Press. Python, many people say is one of the most elegant programming languages in existence: read on to find out why. Also don't miss Linux.com's companion Live chat with Ken McDonald and Darryl Harms today at 11:00 am PDT on IRC in channel #live on irc.openprojects.net.

What is a Module?   Page 1 of 4  >>

Excerpt used with permission. Copyright Manning Publications. Find out much more about "The Quick Python Book" at http://www.manning.com

Modules and Scoping Rules

  • 11.1 What is a module?
  • 11.2 A first module
  • 11.3 The import statement
  • 11.4 The module search path
  • 11.5 Private names in modules
  • 11.6 Library and third-party modules
  • 11.7 Python scoping rules and namespaces

Modules are used to organize larger Python projects. The Python language itself is split into modules to make it more manageable. You don't need to organize your own code into modules, but if you're writing any programs more than a few pages long, or any code that you want to reuse, you should probably do so.

11. 1 What is a module?

A module is a file containing code. A module defines a group of Python functions or other objects. The name of the module is derived from the name of the file.

Modules will most often contain Python source code, but they can also be compiled C or C++ object files. Compiled modules and Python source modules are used in the same way.

A module is just a single file containing related functions, constants, and so forth.

As well as grouping related Python objects, modules help avoid name clash problems. For example, you might write a module for your program called MyModule, which defines a function called reverse. In the same program you might also wish to make use of some-body else's module called OtherModule, which also defines a function called reverse, but which does something different from your reverse function. In a language without modules, it would be impossible to use two different reverse functions. In Python, it's trivial-you simply refer to them in your main program as MyModule.reverse and OtherModule.reverse.

Modules are also used to make Python itself more manageable. Most standard Python functions are not built into the core of the language, but instead are provided via specific modules, which the programmer can load as needed.





What is a Module?   Page 1 of 4  >>