What are modules and how to create modules.

What are modules?

Modules are programs, just like the program we created so far. We usually organize reusable code into modules and Python gives us a good way to manage modules.

One module stores in one file.

Create a .py file under c:/python to store the following code.


# hello.py 
print "Hello, world!" 

The following code imports the hello.py as a module.


import sys 
sys.path.append('c:/python') 
import hello 

A new file appears in this case c:\python\ hello.pyc. The file with the .pyc extension is a compiled Python file for fast loading.

Importing a module several times has the same effect as importing it once.

Reload modules

If you insist on reloading your module, you can use the built-in function reload. It takes a single argument which is the module you want to reload and returns the reloaded module. This may be useful if you change your module and load the module while program is running.

To reload the simple hello module you would use the following:


hello = reload(hello) 

A Simple Module Containing a Function


# hello2.py 
def hello(): 
    print "Hello, world!" 
    

import sys 
sys.path.append('c:/python') 
import hello2 
hello2.hello() 




















Home »
  Python »
    Advanced Features »




Exception Handling
File
Module