1 Modules

Modules allow us to write code, and separate it out from other code into a different file. We can use the import statement to include the code of another file, either in the current directory or in python's search path. What this means is that the file is loaded and run as if its code had been in the place of the import statement. As such, any statements in the file are executed, including function definitions, class definitions, assignments, etc. To import a module, simply type

import <module_name>

where module_name is the name of a python file without the .py extension. The following statment allow us to use a module attribute (function).


Example: The math module provides various mathematical functions. E.g. trigonometric functions, hyperbolic functions, exponent and logarithm functions, and mathematical constants

>>> import math
>>> math.pi
To load selected funtions from a module type

 from <module_name> import funcname 
The contents of a module can be printed out by calling the function dir(module)

[’ doc ’, ’ name ’, ’ package ’, ’acos’, ’acosh’, ’asin’, ’asinh’, ’atan’, ’atan2’, ’atanh’,
’ceil’, ’copysign’, ’cos’, ’cosh’, ’degrees’, ’e’, ’erf’, ’erfc’,
’exp’, ’expm1’, ’fabs’, ’factorial’, ’floor’, ’fmod’, ’frexp’, ’fsum’, ’gamma’, ’hypot’, ’isinf’,
’isnan’, ’ldexp’, ’lgamma’, ’log’, ’log10’, ’log1p’, ’modf’, ’pi’, ’pow’, ’radians’, ’sin’, ’sinh’,
’sqrt’, ’tan’, ’tanh’, ’trunc’]

Selected standard modules

  • cmath: Provides most of the functions found in the math module, but accepts commplex arguments.
    >>> import cmath        
    >>> x,y = 1.0 -2.3j
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'complex' object is not iterable
    >>> x,y = 1.0 -2.3j, -2.5 + 3.2j
    >>> z = x/y
    >>> z
    >>> cmath.asinh(z)
  • random: Provides various methods of choosing random numbers, or making random choices from sequences, using a variety of statistical distributions.
    >>> import random
    >>> random.random()             # get a uniformely distributed random number
                                    # in  [0., 1.]
    >>>> random.randrange(0, 100, 5)   #draw  a random integer from 0 to 1000, 
                                       #only multiple of five
    >>> random.randint(5, 20)    # get a random integer uniformely distributed  
                                 # 3 in  [5, 20]
    >>>random.choice([1,2,'a',4])    # choose a random number in the list
    >>> random.choice('abdgsrt')
    >>> x =[1,2,3,4]
    >>> random.shuffle(x)
    >>> x
    [3, 2, 4, 1]
    >>> random.sample('acgt-ag', 3) # draw a random sample of 3 elements
  • os: Provides operating system related functions, primarily file and process management functions.
    >>> import os
    >>> os.mkdir('new_dir')
    >>> os.chmod('new_dir', 744)
    >>> os.rmdir()
  • sys: Provides a large number of variables and functions dealing with the internals of the python interpreter itself, and the environment in which it was invoked. Specific uses of various sys variables are discussed shortly.

    #importing module
    import sys
    #pick the number of command line arguments
    n = len(sys.argv)
    print "number of arguments %d."%n
    #print the list of arguments
    print 'i \t argument'
    for i in range(n):
          print i, "\t", sys.argv[i]
  • pylab: Provides the tools for plotting and manipulating graphics
    >>>import pylab
    >>>x = pylab.linspace(0, 10, 1000)   # provide a list of 1000 evenly 
                                         #distributed numbers in [0,1]
    >>>y = x**3+x**2-3*x
    >>>z = pylab.cos(x)
    >>>pylab.plot(x,z)    #plotting y against x
    >>>        #displaying the graph
    >>>pylab.plot(x, z)    # plotting z against x
  • numpy: Provides the tools for numerical computations
    import numpy as np
    >>> x = np.arange(6)
    >>> print x
    [0 1 2 3 4 5]
    >>> x/3.
    array([0., 0.33333333, 0.66666667,  1., 1.33333333, 1.66666667])
    >>> x = x.reshape((2,3))
    >>>print x
    [[0 1 2]
     [3 4 5]]
    >>> x = x.transpose()
    >>> print x
    [[0 3]
     [1 4]
     [2 5]]
  • scipy: Provides almost all the tools we will use in this python lecture. It contains all the functions from the Numpy.
    >>> import scipy as sp
    >>> sp.zeros(4)
    array([ 0.,  0.,  0.,  0.])
    >>> sp.ones((2,3))
    array([[ 1.,  1.,  1.],
           [ 1.,  1.,  1.]])
    >>>  x = sp.matrix([[1,2],[-1,0]])
    matrix([[ 1,  2],
            [-1,  0]])
    >>> sp.trace(x)
    >>> y = x[1]
  • scipy.special: Provides routines for special functions such as the airy, elliptic, bessel, gamma, beta, hypergeometric, parabolic cylinder, mathieu, spheroidal wave, struve, erf, and kelvin functions. Import scipy.special and type dir(scipy.special) to find out more.

Creating your own module

Any python script can be reused as a module

Example: Write a module ( to compute the square root of a numbers, and write another program ( that computes the hypotenuse of a right angle triangle.

Variable scope and Namespace

Variables have a limited availability according to the block of statements in which they were originally defined. The scope of a variable is the set of blocks within which it is defined. There are two levels of scope in Python

  • Local scope: A variable is local to a block (or function) when it is accessible only inside that block. Outside that block, the variable is not available.
  • Global scope: A variable is global when it is accessible everywhere in the program.

The Namespace of a module is a dictionary that contains the list of variables and their values. The namespaces are automatically created when the module is imported. There are three levels of namespace in python:

  • Local namespace: Created when a function is called. It contains the variables passed to the function as arguments and the variables created within the function. The namespace is deleted when the function terminates.
  • Global namespace: Created when a module is imported. Variables in a global namespace are accessible to any function within the module.
  • Builtin namespace: Created when the interpreter starts. The functions in these namespace are accessible by any program. When a variable name is encounter during the exsecution of a function, python tries to resolve it by searching in the following order: (1)local namespace, (2) global namespace and (3) builtin namespace. If the name cannot be resolved, python raises a NameError exception
Yves Semegni,
Oct 14, 2011, 5:45 AM
Yves Semegni,
Oct 14, 2011, 5:45 AM
Yves Semegni,
Oct 14, 2011, 5:31 AM
Yves Semegni,
Oct 14, 2011, 5:31 AM