Monday, July 14, 2014

Importing modules

What is Python Module?

When a Python shell starts it only has access to a basic python functions (“int”, “dict”, “len”, “sum”, “range”, ...) “Modules” that contain additional functionality more methods, more reusability and more sharability. Use “import” keyword to tell the Python shell to load a module.

import os, sys
Namespaces are one honking great idea -- let's do more of those! (Zen of Python)
import this

Why importing modules in Python?

The major advantage comes when you split your program into several files for easier maintenance.

How to import modules in Python

A module can be imported by another program to make use of its functionality. This is how we can use the Python standard library as well You can import multiple modules.

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

Normally after module import we can use its containing functions by calling them with refering with the module name followed by period or dot(.) and the function/procedure name.

import modulename
a = modulename.function()

A module can be short-named that is alias for the module.
import modulename as mymod
a = mymod.function()

You can import only the function instead of whole functions in the modules which are not used.
from modulename import function
a = function()

You can also make the function alias.

from modulename import function as f
a = f()

Either you can import all the module content
from modulename import *

The following Python program is going to illustrate that importing the modules. A module can be set of functions defined in a .py file. Here we have experimented with mymath.py program with major math functions definations : multiply, add, sub, div. And these functions can be called in one more Python program where you can test the module function calls after importing them.

"""
File name : mymath.py
The python program is to illustrate the math functions.
"""

def multiply():
 print 'enter 2 numbers'
 a=input('>')
 b=input('>')
 c=a*b
 print 'product of', a, b, 'is', c

def add():
 print 'enter 2 numbers'
 a=input('>')
 b=input('>')
 c=a+b
 print c
 
def sub():
 print 10 - 3
 
def div(x,y):
 print x /y

The following program is invoking the functions that are defined in the mymath.py file.
""""
File Name: testmodule.py
This will give you the execution of all the functions imported from mymath.py

Example:
>>> execfile('c:/pybin/testmod.py')
7
multiply
enter 2 numbers
>3
>4
product of 3 4 is 12
Addition...
enter 2 numbers
>5
>6
11

"""

from mymath import *
 
mymath.sub()
print 'multiply'
multiply()
print 'Addition...'
add()


importing packages


Package is a directory of Python programs that have module code. A package is a collection of modules in directories that give a package hierarchy. __init__.py makes a directory to a package.
import dir1.dir2.module
from dir1.dir2.module import function
Use dot(.) instead f (/) - dir/dir2/module
from dir1.dir2.dir3.mod import function
 function()
import dir1.dir2.dir3.mod as mod
 mod.function()

The PYTHONPATH usage

PYTHONPATH is an environment variable set with the locations where the Python interpreter searches for user created modules. Typically, the module search path is defined as:
 export PYTHONPATH=.:/usr/local/lib/pythonX.X 
which is the current directory and library path, where you can add your Python module path say /home/sujith/pybin/modules appended to this PYTHONPATH. Let me tell you the trick to understand a module. You can get the module path from which they are imported using str() function on the module. How do we know it is a module? Use dir() function.

Generating Bytecode from .py

There could be bulk number of Python source files you might get in some cases where you need to use them in your source. To avoid slow interpretation we can create the intermediary code that is bytecode from each .py source file by compiling them. py_compile module we can generate the bytecode. This py_compile module have two important methods: compile() and compileall().Here compileall() function used to compile all Python files in an entire directory tree.
import py_compile
py_compile.compile('myscript.py')
or else you can do that at your command prompt as well as shown:
python -m py_compile myscript.py
python –m py_compile A.py B.py C.py  
python –m compileall –l pybin

Dynamic module loading

Here we have another dynamic trick that might be useful when you need to use some module which is in separate path(not in the PYTHONPATH or in current path) and you need in Python script/Shell; then you can use standard sys module. First you need to import sys (sys is a standard python module) and then append the new path to sys.path that is a string list.
import sys
sys.path.append('/home/sujith/pybin')

The __import__ method

myos = __import__(“os”) (O) To support some dynamic features.
myos=__import__("os")
>>> myos


>>> myos.getloadavg()
(0.14, 0.21, 0.51)
>>> myos.getgroups()
[4, 24, 27, 30, 46, 109, 124, 1000]
>>> myos.getcwd()
'/home/pavanbsd'


The __name__ of module


__name__ is an attribute for a module. A module ‘s __name__ will set to the string "__main__" when you start this module as a program. If you import the module, the module’s name will set to the module’s file name without .py suffix. The simple rule: your starting program have __name__ is set to “__main__”, otherwise it is just the module file name without .py suffix. To avoid ambiguity for Python interpretor we can write an if condition for main module.
if __name__=="__main__":
    call_fun()


Here we can do enhance our packages and sub-packages customized to build more powerful script utilities.

No comments:

Post a Comment

DevOps Foundation course

DevOps Foundation course
Join us to learn DevOps from the Beginning