Modules

In Python, a module is simply a file containing classes and functions. By importing the file in your session or script, the functions and classes become usable.

Introduction

Python comes with many different libraries by default. You may also want to install more of those for specific purposes, such as optimization, plotting, reading/writing file formats, image handling, and so on. NumPy and SciPy are two important examples of such libraries, matplotlib for plotting is another one. At the end of this chapter, we will list some useful libraries.

To use a library, you may either:

  • Load only certain objects from a library, for example from NumPy:
            from numpy import array, vander
  • Or load the entire library:
            from numpy import *
  • Or give access to an entire library by creating a namespace with the library name:
            import numpy
            ...
            numpy.array(...)

    Prefixing a function from the library with the namespace gives access to this function and distinguishes this function from other objects with the same name.

Furthermore, the name of a namespace can be specified together with the import command:

import numpy as np
...
np.array(...)

Which option you use affects the readability of your code as well as the possibilities for mistakes. A common mistake is shadowing:

from scipy.linalg import eig
A = array([[1,2],[3,4]])
(eig, eigvec) = eig(A)
...
(c, d) = eig(B) # raises an error

A way to avoid this unintended effect is to use import:

import scipy.linalg as sl
A = array([[1,2],[3,4]])
(eig, eigvec) = sl.eig(A) # eig and sl.eig are different objects
...
(c, d) = sl.eig(B)

Throughout this book, we have used many commands, objects, and functions. These were imported into the local namespace by statements such as:

from scipy import *

Importing objects in this manner does not make the module from which they are imported evident. Some examples are given in the following table (Table 11.1):

Libraries

Methods

numpy

array, arange, linspace, vstack, hstack, dot, eye, identity, and zeros.

numpy.linalg

solve, lstsq, eig, and det.

matplotlib.pyplot

plot, legend, and cla.

scipy.integrate

quad.

copy

copy and deepcopy.

Table 11.1: Examples of importing objects

Modules in IPython

IPython is used under code development. A typical scenario is that you work on a file with some function or class definitions which you change within a development cycle. For loading the contents of such a file into the shell, you may use import but the file is loaded only once. Changing the file has no effect on later imports. That's where IPyhthon's magic command run enters the stage.

The IPython magic command

IPython has a special magic command named run that executes a file as if you ran it directly in Python. This means that the file is executed independently of what is already defined in IPython. This is the recommended method to execute files from within IPython when you want to test a script intended as a standalone program. You must import all you need in the executed file in the same way as if you were executing it from the command line. A typical example of running code in myfile.py is:

from numpy import array
...
a = array(...)

This script file is executed in Python by exec(open('myfile.py').read()). Alternatively, in IPython the magic command run myfile can be used if you want to make sure that the script runs independent of the previous imports. Everything that is defined in the file is imported into the IPython workspace.

The variable __name__

In any module, the special variable __name__ is defined as the name of the current module. In the command line (in IPython), this variable is set to __main__, which allows the following trick:

# module
import ...

class ...

if __name__ == "__main__":
   # perform some tests here

The tests will be run only when the file is directly run, not when it is imported.

Some useful modules

The list of useful Python modules is vast. In the following table, we have given a very short segment of such a list, focused on modules related to mathematical and engineering applications (Table 11.2):

Module

Description

scipy

Functions used in scientific computing

numpy

Support arrays and related methods

matplotlib

Plotting and visualization with the import submodule pyplot

functools

Partial application  of functions

itertools

Iterator tools to provide special capabilities, like slicing to generators

re

Regular expressions for advanced string handling

sys

System specific functions

os

Operating system interfaces like directory listing and file handling

datetime

Representing dates and date increments

time

Returning wall clock time

timeit

Measures execution time

sympy

Computer arithmetic package (symbolic computations)

pickle

 Pickling, special file in- and output format

shelves

 Shelves, special file in- and output format

contextlib

Tools for context managers

Table 11.2: A non-exhaustive list of useful Python packages for engineering applications

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.4.174