An Introduction to Python

Python is an extensible, high-level, interpreted, object-oriented programming language. Ready for use in the real world, it's also free.
Python Has Real Class

With the next example, I'll try to demonstrate some of these features. The StackingThings class will allow the user to stack items on top of each other until a breaking point is reached.

1       #!/usr/local/bin/python
3       StackingException = `StackingException'
5       class StackingThings:
6       names = (`llama', `spam', `16 ton weight',
7       `dead parrot')
8       weights = {}
9       weights[`llama']         =     300
10      weights[`spam']          =       1
11      weights[`16 ton weight'] =   32000
12      weights[`dead parrot']   =       2
13      breakpt = {}    # breaking points
14      breakpt[`llama']         =     200
15      breakpt[`spam']          =    1000
16      breakpt[`16 ton weight'] = 1000000
17      breakpt[`dead parrot']   =      15
19      def _ _init_ _(self):
20      self.items_stacked = []
21      def add(self, item):
22              if item not in self.names:
23                      raise StackingException, \
24                              item+`not a stackable object'
25      self.items_stacked.insert(0, item)
26      try:
27              self.test_strength(item)
28                except StackingException, val:
29                      print item, val
30      def test_strength(self, item):
31          wt = 0
32          bp = 1000000
33          for i in self.items_stacked:
34              wt = wt + self.weights[i]
35              if wt > bp:
36                 self.items_stacked.remove(item)
37                 raise StackingException, \
38                    `exceeds breaking point!'
39              bp = self.breakpt[i]
41      # user code to test StackingThings class
43  s = StackingThings()
45  s.add(`llama')
46  s.add(`spam')
47  s.add(`spam')
48  s.add(`spam')
49  s.add(`dead parrot')
50  s.add(`16 ton weight')
52  print `items stacked = ', s.items_stacked
54  try:
55      s.add(`bad object')
56  except StackingException, msg:
57      print `exception:', msg

This script produces the following output:

16 ton weight exceeds breaking point!
items stacked =  [`dead parrot', `spam', `spam',
     `spam', `llama']
exception: bad object not a stackable object

The StackingThings class itself consists of 3 methods: _ _init_ _(), add(), and test_strength(). When initiating StackingThings, we use the special __init__ method to create its initial state by initializing the list of stacked items: items_stacked = []. The add() method is essentially the only method that is accessed by the user of StackingThings. And test_strength() is called by add() to verify that we have not exceeded our breaking point.

The first argument to each method in our example is called self. This is just a convention, but it makes our code much more readable. The first argument to a Python method is used in a somewhat similar fashion as this keyword in C++.

Python provides for exception handling, both built-in (i.e. ZeroDivisionError, TypeError, NameError, etc.) and user-defined exceptions. The latter is especially useful in developing robust classes. Python uses the try/except syntax for exception handling:

except ZeroDivisionError, val:
    print `Whoops:', val

Our add() method is used to try an exception in test_strength() and raise an exception when we pass it an illegal stacking item.

Two of the built-in methods for Python lists that are demonstrated in the example on lines 25 and 36 are insert() and remove(). Other supported operations on list objects include append(), count(), index(), reverse(), and sort().

The data attributes may be accessed by the methods of the class as well as the user code: Either print self.names (within a class method) or print s.names (from the user code) will print the list of legal stacking things:

[`llama', `spam', `16 ton weight', `dead parrot']
Look It Up!

Dictionaries (associative arrays to all you awk/perl hackers) are one of the most useful Python data types. Unlike a normal array, which is indexed by number, associative arrays are indexed by strings. The value of this utility is worth describing in some detail.

I frequently deal with ICD-9-CM codes in medical applications. These codes are usually numeric, but sometimes alphanumeric. They usually have a decimal point, but sometimes don't. Some of the codes may be further sub-divided into additional ICD-9 codes. Furthermore, codes are added and deleted periodically, but most don't change. Normally, the lookup of ICD-9 codes will be done in a relational database, but it is also convenient to use small data sets within an application. For example, given the dictionaries icd9 and subdivide:

   x              subdivide[x]          icd9[x]
  ---             ------------    -------------------------
  `692'                 1         `Contact dermatitis'
  `692.0'               0         `Due to detergents'
  `692.2'               0         `Due to solvents'
  `692.7'               1         `Due to solar radiation'
  `692.70'              0         `Unspecified dermatitis'
  `692.71'              0         `Sunburn'
  `692.72'              0         `Other: Photodermatitis'

We can manipulate the ICD-9 codes in the following manner:

for code in icd9.keys():
  if subdivide[code]:
      print `ICD-9',code,'may be further subdivided'
      print `Description for',code,`is:',icd9[code]

This would produce the following output:

ICD-9 692.7 may be further subdivided
Description for 692.70 is: Unspecified dermatitis
Description for 692.0 is: Due to detergents
ICD-9 692 may be further subdivided
Description for 692.71 is: Sunburn
Description for 692.2 is: Due to solvents
Description for 692.72 is: Other: Photodermatitis

Lines 8-17 of our StackingThings example use dictionaries, but the initialization was broken into several lines for clarity. This could be reduced to:

weights = {`llama':300, `spam':1, \
    `16 ton weight':32000, `dead parrot':2}
breakpt = {`llama':200, `spam':1000, \
    `16 ton weight':1000000, `dead parrot':15}

Finally, inheritance is provided in Python, although it is not demonstrated in this example. The derived class may override methods of its base class or classes (yes, multiple inheritance is supported in a limited form). In C++ parlance, all methods in a Python class are “virtual”.


White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState