Python notes

Here are a few python tricks

§    Eliminate tail recursion

Formerly at http://mail.python.org/pipermail/python-list/2002-June/107487.html
import types

TRE_magic = "TRE magic string"

def TREcont(fn, *rest): 
        def fncont(*rest): 
            return fn(cont=TREcont, *rest)
        return (TRE_magic, fncont, rest)

def TRE(fn, *rest):
        x = fn(cont=TREcont, *rest)
        while isinstance(x, types.TupleType) and (x[0] is TRE_magic):
          x = x[1](*x[2])
        return x

def factorial(n,acc=1,cont=TRE):
        if n <= 1: return acc
        else:      return cont(factorial,n-1,acc*n)

§    Interactive help

>>> dir()
>>> dir('__builtins__')
>>> help()
help> keywords
help> modules

§    List all keywords

import keyword; print keyword.kwlist

(2002-2005)


Return to parent directory.