Introduction to Python – Modules

If you are interested to learn about the Python function

A module allows you to logically organize your Python code. A file containing a set of functions you want to include in your application. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference. Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code. Modules refer to a file containing Python statements and definitions. A file containing Python code, for example: , is called a module, and its module name would be example . We use modules to break down large programs into small manageable and organized files.

What are Python modules?


The Python code for a module named aname normally resides in a file named Here’s an example of a simple module,

def print_func( par ):
   print "Hello : ", par

The import Statement

You can use any Python source file as a module by executing an import statement in some other Python source file. The import statement is used to import all the functionality of one module into another. Here, we must notice that we can use the functionality of any python source file by importing that file as the module into another python source file. The import has the following syntax −

import module1[, module2[,... moduleN]

When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module. For example, to import the module, you need to put the following command at the top of the script −


# Import module support
import support

# Now you can call defined function that module as follows

When the above code is executed, it produces the following result −

Hello : Zara

A module is loaded only once, regardless of the number of times it is imported. This prevents the module execution from happening over and over again if multiple imports occur.

The from…import Statement

Python’s from statement lets you import specific attributes from a module into the current namespace. Instead of importing the whole module into the namespace, python provides the flexibility to import only the specific attributes of a module. The from…import has the following syntax −

from modname import name1[, name2[, ... nameN]]

For example, to import the function fibonacci from the module fib, use the following statement −

from fib import fibonacci

This statement does not import the entire module fib into the current namespace; it just introduces the item fibonacci from the module fib into the global symbol table of the importing module.

The from…import * Statement

It is also possible to import all names from a module into the current namespace by using the following import statement. Instead of importing the whole module into the namespace, python provides the flexibility to import only the specific attributes of a module −

from modname import *

This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly.

Locating Modules

When you import a module, the Python interpreter searches for the module in the following sequences −

  • The current directory.
  • If the module isn’t found, Python then searches each directory in the shell variable PYTHONPATH.
  • If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/.

The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default.


The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable PATH. Here is a typical PYTHONPATH from a Windows system −

set PYTHONPATH = c:\python20\lib;

And here is a typical PYTHONPATH from a UNIX system −

set PYTHONPATH = /usr/local/lib/python

Namespaces and Scoping

Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values). A Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable. Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions. Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local. Therefore, in order to assign a value to a global variable within a function, you must first use the global statement. The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable. For example, we define a variable Money in the global namespace. Within the function Money, we assign Money a value, therefore Python assumes Money as a local variable. However, we accessed the value of the local variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the global statement fixes the problem.


Money = 2000
def AddMoney():
   # Uncomment the following line to fix the code:
   # global Money
   Money = Money + 1

print Money
print Money

The dir( ) Function

The dir() built-in function returns a sorted list of strings containing the names defined by a module. The dir() function returns a sorted list of names defined in the passed module. This list contains all the sub-modules, variables and functions defined in this module. The list contains the names of all the modules, variables and functions that are defined in a module. Following is a simple example −


# Import built-in module math
import math

content = dir(math)
print content

When the above code is executed, it produces the following result −

['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 
'sqrt', 'tan', 'tanh']

Here, the special string variable __name__ is the module’s name, and __file__ is the filename from which the module was loaded.

The globals() and locals() Functions

The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called. If locals() is called from within a function, it will return all the names that can be accessed locally from that function. If globals() is called from within a function, it will return all the names that can be accessed globally from that function. The return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function.

The reload() Function

When the module is imported into a script, the code in the top-level portion of a module is executed only once. a module is loaded once regardless of the number of times it is imported into the python source file. However, if you want to reload the already imported module to re-execute the top-level code, python provides us the reload() function. Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The reload() function imports a previously imported module again. The syntax of the reload() function is this −


Here, module_name is the name of the module you want to reload and not the string containing the module name. For example, to reload hello module, do the following −


Packages in Python

A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on. Consider a file available in Phone directory. This file has following line of source code −


def Pots():
   print "I'm Pots Phone"

Similar way, we have another two files having different functions with the same name as above −

  • Phone/ file having function Isdn()
  • Phone/ file having function G3()

Now, create one more file in Phone directory −

  • Phone/

To make all of your functions available when you’ve imported Phone, you need to put explicit import statements in as follows −

from Pots import Pots
from Isdn import Isdn
from G3 import G3

After you add these lines to, you have all of these classes available when you import the Phone package.


# Now import your Phone Package.
import Phone


When the above code is executed, it produces the following result −

I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone

In the above example, we have taken example of a single functions in each file, but you can keep multiple functions in your files. You can also define different Python classes in those files and then you can create your packages out of those classes.

Scope of variables

In Python, variables are associated with two types of scopes. All the variables defined in a module contain the global scope unless or until it is defined within a function. All the variables defined inside a function contain a local scope that is limited to this function itself. We can not access a local variable globally. If two variables are defined with the same name with the two different scopes, i.e., local and global, then the priority will always be given to the local variable. Consider the following example.


name = "john"  <strong>def</strong> print_name(name):   
   <strong>print</strong>("Hi",name) #prints the name that is local to this function only. 
 name = input("Enter the name?")  print_name(name)  


Hi David 

Python packages

The packages in python facilitate the developer with the application development environment by providing a hierarchical directory structure where a package contains sub-packages, modules, and sub-modules. The packages are used to categorize the application level code efficiently. Let’s create a package named Employees in your home directory. Consider the following steps.

1. Create a directory with name Employees on path /home.

2. Create a python source file with name on the path /home/Employees.

  1. def getITNames():  
  2.     List = [“John”, “David”, “Nick”,    “Martin”]  
  3.     return List;  

3. Similarly, create one more python file with name and create a function getBPONames().

4. Now, the directory Employees which we have created in the first step contains two python modules. To make this directory a package, we need to include one more file here, that is which contains the import statements of the modules defined in this directory.

  1. from ITEmployees import getITNames  
  2. from BPOEmployees import getBPONames  

5. Now, the directory Employees has become the package containing two python modules. Here we must notice that we must have to create inside a directory to convert this directory to a package.

6. To use the modules defined inside the package Employees, we must have to import this in our python source file. Let’s create a simple python source file at our home directory (/home) which uses the modules defined in this package.

  1. import Employees  
  2. print(Employees.getNames())  


['John', 'David', 'Nick', 'Martin']

We can have ree sub-packages as Admin, Librarian, and Student. The sub-packages contain the python modules.

Introduction to Python – Modules
Show Buttons
Hide Buttons