Tutorial: Python

The full title of this tutorial was, “Totally Awesome Computing: Python as a General-Purpose Programming Language.” I signed up for this talk primarily because it was given by Chuck Allison, whose name I recognized from the C++ community.

Chuck started from square one, which was great since I’m a total Python n00b. However, I won’t attempt to describe all the details of Python syntax here. (There are plenty of resources online already.) Instead, I’ll focus on a few things that I found new and interesting.


List Comprehensions
List comprehensions are a neat way to generate lists and resemble the set-builder notation that you probably remember from a discrete math course (think “for all” and “such that”). The implementation of quicksort using list comprehensions is a thing of beauty. Sure it’s a toy (note the choice of pivot), but you have to admit that it’s dazzlingly succinct:


   def qsort(L):
      if len(L) <= 1: return L
      return qsort([lt for lt in L[1:] if lt = L[0]])

Generators
Generators are a peculiar kind of higher-order function. They return callable entities which, in turn, retain their state between invocations. I realize that the previous sentence may not parse well — so just ignore it for now and instead take a look at Chuck’s example:


   def countgen():
      count = 0
      while True:
         count += 1
         yield count

   f = countgen()
   f.next()  # returns 1
   f.next()  # returns 2
   f.next()  # returns 3

Generators employ the yield statement, which is like a return, except that state is preserved. Calling the next() function on a generator simply picks up where the function left off. They are also iterable for easy looping.

Type System
Python uses duck typing, however there do not seem to be implicit type conversions. So, whereas in Perl you might say:


   $i = "1";  # a string
   $i += 1;
   print $i;  # prints 2

To achieve the same thing in Python you’d have to say:


   i = "1"
   i = int(i)
   i += 1
   print i

Perl saves a line, but there are certainly trade-offs. I need to think about this one for a bit before attempting to make any kind of judgment. It seems important to consider the fact that Python overloads the + operator for addition and concatenation, whereas Perl uses separate operators.

Decorators
Python has some syntactic sugar for higher order functions called decorators, and uses this feature to support things like class methods and synchronized functions. (GoF initiates beware: this has almost nothing to do with the decorator design pattern.) Decorators look something like this:


   @bar
   def foo():
      #...

In this example, we are defining a new function foo which is automatically “decorated” with bar. This is a little confusing until you learn that bar is just a function (or other callable entity) and the syntax above is just sugar for:


   def foo():
      #...
   foo = bar(foo)

For a really slick use-case, take a look at this memoize decorator from ASPN. Before you ask: yes, recursive calls are handled properly.

For more on decorators, check out the PEP 318 spec.

Misc
Python has some fancy and unexpected parameter passing stuff. It has suppport for both positional and named parameters, the latter inheriting their names automatically from the function prototype. Parameters can be passed in tuple or dictionary form, and there is built in support for packing and unpacking these at the callee and caller, respectively.

OOP purists may bemoan the fact that all class attributes are public, although there is a double-underscore trick which helps here (pseudo-privacy). I can’t imagine having to type all those underscores very often, but I guess that’s the point.

Python seems rather heavily dictionary/hashmap based. To wit, this is how namespaces, classes, etc, are actually implemented. I guess this makes things simpler, however there does appear to be some complexity around binding (see the LEGB rule).

Summary
One of the great things about OOPSLA is discovering new languages, and one of the great things about discovering new languages is learning new language features. Python has a bunch of features that I have not previously encountered. If I can wire this stuff into my brain, I’m sure I’ll be more effective in any language. I’m looking forward to spending some time with Python. As Borat would say, “I am very excite!”

Advertisements


%d bloggers like this: