Sunday, July 26, 2015

Python - Modules

A Module or a Package allows you to logically arrange or organize your code. This allows us to group related code into a module which makes the code easier to understand and code.

A module in a Python is an Python object which can be used to bind and reference.

A Module in a Python consists of a Python code. A module can define functions, classes, variables along with a run able code.

Now lets see a basic Example on how to use Python Modules. Write a below sample python Function in a file and save that as support.py

def printFun(str):
    print "Hello , This is Passed String " , str
    return

Once the file is saved open the Python interpreter and invoke the commands as,

>>> import support
>>> support.printFun("Python")
Hello, This is Passed String Python

We can see after importing the module support, we can directly call methods implements inside the support python code.

Import -  We can use any python source file as a module by executing an import statement in some other python code using the import statement. The syntax looks as

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

Normally when the python encounters with the import statement, the interpreter imports the module as it is present in the search path. The Search path is a list of directories that the interpreter searches before importing a module.

Python does contain some default Environment variables for searching for the modules

PYTHONHOME - Location of standard libraries
PYTHONPATH - Additions to standard search path for modules
PYTHONSTARTUP - Interactive mode; commands run before first input is prompted FOR

From – A from Statement allows us to use a specific attributes from a module into the current name space or code. The syntax looks as

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

The above example can be re-written as

>>> from support import printFun
>>> printFun("Python")
Hello , This is Passed String  Python

All modules can be imported using - From support import *

Locating Modules
When a module is imported, python interpreter searches for the modules in the following way,

1) First it searches in the Current directory
2) If not available, it goes and searches in the location set by PYTHONPATH
3) If the module is not available even in the PYTHONPATH, it then searches the location
    /usr/local/lib/python.

The location search path is set in the module sys. We can get this using sys.pathvariables. The sys.path variables contains the current directory and installation path


The PYTHONPATH Variable - The PYTHONPATH is an environment variable, consisting of a list of directories.

No comments :

Post a Comment