Sunday, 20 March 2016

Modules in python

Modules in python with examples:

In python, modules play a vital role.

A module is a Python object with arbitrarily named attributes that you can bind and reference. A module can define functions, classes and variables. A module can also include runnable code.Python module allows us to logically organize our Python code. Grouping related code into a module makes the code easier to understand and use. In other words, a module is a file consisting of Python code.

Example for the module in python:

The Python code for a module named aname normally resides in a file named
Let us see the below module named as

def DUMP_func( Var ):

   print "Hello : ", Var

The import Statement in python:

You can use any Python source file as a module by executing an import statement in some other Python source file.
import module1[, module2[,... moduleN]

When the interpreter encounters an import statement, it imports the module if the module is present in the search path.
The interpreter searches for the importing module in the search path which contains a list of directories. For example, to import the module, you need to put the following command at the top of the script −
# Import module SimpleModule
import SimpleModule
# Now you can call defined function that module as follows
SimpleModule.print_func("Test Sample")
The result of the above code is
Hello : Test Sample

Characteristics of the Modules:

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

The from...import Statement in python:

Python's from statement lets you import specific attributes from a module into the current namespace. The from...import has the following syntax −
from modname import name1[, name2[, ... nameN]] 
For example, to import the function TestModule from the module TestMod, use the following statement −
from TestMod import TestModule 
This statement does not import the entire module TestMod into the current namespace; it just introduces the item TestModule from the module TestMod into the global symbol table of the importing module.

The from...import * Statement in python:

It is also possible to import all names from a module into the current namespace by using the following import statement −
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.

No comments: