If it won't be simple, it simply won't be. [Hire me, source code] by Miki Tebeka, CEO, 353Solutions

Sunday, June 25, 2006

Quick ID Generator

Sometimes I find myself in the need to assign unique id for objects, count from itertools is a quick solution.

from itertools import count

next_id = count(0).next

print next_id() # 0
print next_id() # 1
print next_id() # 2

Thursday, June 15, 2006

Using distutils to build SWIG packages

SWIG is a software development tool that connects programs written in C and C++ with a variety of high-level programming languages.

Using SWIG makes connecting libraries written in C/C++ to Python very simple.
However you also need to compile the SWIG generated sources with all the right compiler flags (for finding the Python header files and libraries).

We can use distutils to save us this work as well.

Assume our C library is hello.c and our SWIG interface definition is in hello.i, write the following code in setup.py

from distutils.core import setup, Extension

setup(
    ext_modules = [
        Extension("_hello", sources=["hello.c", "hello.i"])
    ]
)

Note the underscore in the module name, SWIG generated a hello.py which will call import _hello somewhere.

To compile run python setup.py build_ext -i.

For a long article on SWIG and Python see here.

EDIT (3/2010): UnixReview is no longer with us, I'll try to locate the article.

Tuesday, June 06, 2006

Visitor Design Pattern

The Visitor Design Pattern can be written a bit differently in Python using its rich introspection abilities.

(This is a modified version of the code found in compiler/visitor.py in the Python standard library)

Blog Archive