Monthly Archives: January 2012

List comprehensions

List comprehensions provide a concise way to create lists from existing lists. Each list comprehension consists of an expression followed by a for clause, then zero or more for or if clauses. The result will be a list resulting from evaluating the expression in the context of the for and if clauses which follow it.

The following are common ways to describe lists (or sets, or tuples, or vectors) in mathematics.

Lists can contain any type of elements, including strings, nested lists and functions. We can even mix different types within a list.
The following works on a list of strings and produces a list of lists.

The following is also an example of nested list comprehension:


Unit testing in Python

According to wikipedia: In computer programming, unit testing is a method by which individual units of source code are tested to determine if they are fit for use. A unit is the smallest testable part of an application. In procedural programming a unit could be an entire module but is more commonly an individual function or procedure. In object-oriented programming a unit is often an entire interface, such as a class, but could be an individual method.

This post is about testing in Python, mainly using the Python standard library testing framework unittest. For an example to test, first import the Unit Test module by:

import unittest

unittestis an object oriented framework based around test fixtures. In unittest the test fixture is the TestCase class. To write a testcase class, we have to write a class that derives from the TestCase class of the unittest module. On the class statement, the base class (or classes) goes in parentheses after the name of the class. The usual four-phase unit test includes Setup, Exercise, Verify and Teardown.

The snapshot of my sample unit testing program is shown below:

In the above program add is a simple adding function to demo unittest. MyTest is the class in which all functions will be ran by unittest. The function setUp will always be ran in order to setup the test environment before all the tests have run. The function tearDown will always be ran in order to cleanup the test environment after all the tests have run. After that, the function beginning with ‘add’ will be ran as a unit test. AssertEqual checks the values given in the parentheses are equal. The TestCase class provides a number of methods to check for and report failures, such as:

assertEqual (a,b) → a == b

assertNotEqual (a,b) → a != b

assertTrue (x) → bool(x) is True

assertFalse(x) → bool(x) is False

assertIs (a,b) → a is b

assertIsNot(a,b) → a is not b

assertIn (a,b) → a in b

assertNotIn (a,b) → a not in b

When we run the above program, we get an output like this:

If there is error in the output or if it is not compiled properly, it will be printed in the terminal. Here , the code is correct. So, we get the output as ‘OK’.

The Blog

The latest news on and the WordPress community.