Product SiteDocumentation Site

Chapter 13. Modules

13.1. Introduction
13.2. Importing modules
13.3. Default modules
13.4. Submodules
13.5. Module os

In this chapter we are going to learn about Python modules.

13.1. Introduction

Still now when ever we wrote code in the python interpreter, after we came out of it, the code was lost. But in when one writes a larger program, people breaks their codes into different files and reuse then as required. In python we do this by modules. Modules are nothing files with Python definitions and statements. The module name is same as the file name without the .py extension.

You can find the name of the module by accessing the __name__ variable. It is a global variable.

Now we are going to see how modules work. Create a file called bars.py. Content of the file is given bellow.
"""
Bars Module
============

This is an example module with provide different ways to print bars.

"""

def starbar(num):
    """
    Prints a bar with *

    :arg num: Length of the bar

    """
    print '*' * num

def hashbar(num):
    """
    Prints a bar with #

    :arg num: Length of the bar

    """
    print '#' * num

def simplebar(num):
    """
    Prints a bar with -

    :arg num: Length of the bar
    
    """
    print '-' * num


Now we are going to start the python interpreter and import our module.
>>> import bars
>>>

This will import the module bars. We have to use the module name to access functions inside the module.
>>> bars.hashbar(10)
##########
>>> bars.simplebar(10)
----------
>>> bars.starbar(10)
**********