Assertions in Python

January 26, 2009

Keeping track of your variables gets weirdly difficult with even vaguely large projects. Especially when worrying about things like integer division (try 1/2) which can seriously affect your results. So I’ve been getting into assertions. These are little checks that represent your understanding of the variable. So if you have a matrix that you know is square then we can encode this understanding before we try to operate on the matrix. For example, consider some function isposdef() acting on a square matrix A:

def isposdef(A):
	assert type(A) is matrix
	assert A.shape[0] == A.shape[1]

They only take seconds to write but they can save you hours and hours of debugging. I’m trying to get into the habit of writing assertions on every single argument that is passed into a function and on every variable that’s returned by a function. They’re falling into four categories:

  • type assertions: making sure everything is the correct type
  • shape assertions: for matrices mostly, to enforce things like being column vectors
  • consistency assertions: again for matrices – making sure everything’s the correct size with respect to one another
  • value assertions: making sure values are within an allowable range, for example that a particular matrix has negative eigenvalues.

One thing to note is that you shouldn’t be using assertions to test user input. These are for (‘preventative’) debugging – if you know something about a variable then you should express it. If you need to check for user input, proper checks should be implemented. A funky thing about assertions is that you can turn all of them off for production code! So you don’t need to worry about writing millions of assertions – they’re not going to slow you down any in the end.

Along these lines, then, here are two little matrix tests:

def iscolvector(x):
	assert type(x) is matrix
	return x.shape[1] == 1
def issquarematrix(X):
	assert type(X) is matrix
	return X.shape[0] == X.shape[1]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: