Python Modules

Introduction

  • Python allows you to split a program into modules that can be reused in other Python programs.
  • A module is a file containing Python definitions and statements.
  • There are also many standard modules.
  • Definitions from a module can be imported into other modules or into the main module.
  • Within a module, the module’s name (as a string) is available as the value of the global variable name.

Example

# Fibonacci numbers module
 
def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while b < n:
        print b,
        a, b = b, a+b
 
def fib2(n): # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while b < n:
        result.append(b)
        a, b = b, a+b
    return result

Then in the Python interpreter:

>>> import fibo
 
>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'
>>> fib = fibo.fib
>>> fib(500)

Module Statements

  • A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module is imported somewhere.

Standard Modules

Packages

  • Structuring Python’s module namespace by using “dotted module names”.
  • When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.
  • The init.py files are required to make Python treat the directories as containing packages
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.