Home > Articles > Open Source > Python

  • Print
  • + Share This
Like this article? We recommend


As your programs grow in size, you'll probably want to break them into multiple files for easier maintenance. To do this, Python allows you to put definitions in a file and use them as a module that can be imported into other programs and scripts. To create a module, put the relevant statements and definitions into a file that has the same name as the module. (Note: The file must have a .py suffix.) For example:

# file : div.py
def divide(a,b):
  q = a/b    # If a and b are integers, q is an integer
  r = a - q*b
  return (q,r)

To use your module in other programs, you can use the import statement:

import div
a, b = div.divide(2305, 29)

import creates a new namespace that contains all the objects defined in the module. To access this namespace, simply use the name of the module as a prefix, as in div.divide() in the preceding example.

If you want to import a module using a different name, supply the import statement with an optional as qualifier as follows:

import div as foo
a,b = foo.divide(2305,29)

To import specific definitions into the current namespace, use the from statement:

from div import divide
a,b = divide(2305,29)    # No longer need the div prefix

To load all of a module's contents into the current namespace, you can also use the following:

from div import *

Finally, the dir() function lists the contents of a module and is a useful tool for interactive experimentation, since it can be used to provide a list of available functions and variables:

>>> import string
>>> dir(string)
['__builtins__', '__doc__', '__file__', '__name__', '_idmap',
 '_idmapL', '_lower', '_swapcase', '_upper', 'atof', 'atof_error',
 'atoi', 'atoi_error', 'atol', 'atol_error', 'capitalize',
 'capwords', 'center', 'count', 'digits', 'expandtabs', 'find',
  • + Share This
  • 🔖 Save To Your Account