Type Assertions in Python

Python is a dynamically typed language, meaning that it is not necessary to declare the types of variables. This makes Python programs concise and easy to write, but when writing significant code in Python I find myself wanting type declarations both as documentation and as runtime sanity checks.

Here's a simple way to add type declarations to Python in the form of runtime assertions. An object's type is declared by calling a function

_typecheck(argNum, object, typespec)

where object is the Python object to check and typespec is a type specification (defined below). argNum, if positive, is used in formatting error messages. For example, assuming the __debug__ system variable is True,

_typecheck(1, myVar, int)

checks that myVar is an integer. If it's not, an exception is raised:

TypeError: argument 1: expecting <type 'int'>

That's all there is to it. The nifty part is that type specifications are pretty flexible, being similar to Common Lisp type specifiers, which nicely correlates with the kinds of flexible data structures one typically encounters in Python. A type specification can be:

Here's the code: typecheck.py

created 2005-02-07; last modified 2009-01-25 08:09