i

Python Programming

Modules in Python

The module permits you to logically organize the Python code. A grouping related code into the module makes code easier to understand/use. The module is a Python object with arbitrarily named attributes that can bind and reference. The module may also include run-able code.

Example

The Python code for a module named a name generally save in any file like aaname.py. Here's an example of the simple module, help.py

The import-Statement

We can use Python source file as a module by executing an import statement in the some other Python source file. The import has the following syntax −

import module[, module[,... moduleN]

The interpreter encounters an import statement and imports the module if the module present in the search path. The search path is a list of directories that interpreter searches before importing the module. For example, to import the module helpp.pyyou need to put following command top of script:

Output:

Hello Python : Zara

The from-import Statement

The python's from statement lets you import the specific attributes from the module into the current namespace. The from-import has following syntax:

from mod-name import name[, name[, ... nameN]]

For example, to import function Fibonacci from module fibo, use statement:

from fibo import Fibonacci

This statement not imports the entire module fibo into the current namespace but just introduces the item fibonacci from module fibo into the global symbol table of the importing module.

fromimport * (statement)

Also possible to import names from a module into current name-space by using following import statement:

from mod-name import *

It provides an easy way to import all items from a module into current namespace.

Locating-Modules

Whenever you import a module python interpreter searches for the module in the following way:

•    The current-directory.

•    If module isn't found, Python searches each directory in the shell variable PYTHONPATH.

•  Failing this python checks the default path. On UNIX, default path is normally /usr/local/lib/python/.

Module search path is stored in system module sys as sys.path (variables). sys.path (variables) containscurrent directory, PYTHONPATH / installation-dependent default.