Thursday, September 20, 2007

Python Problems

I love Python---it's a fantastic language. Still, it does have a few annoyances, one of which I encountered while dealing with very large integers. I've been frustrated for a while that ints and longs are considered to be different types, as opposed to (for example) one being a subclass of the other. Recently when doing typechecking (which, I understand, should be avoided as much as possible in Python) I ultimately ended by sticking in the gem:
assert isinstance(int(x), int)
Now, to me, this looks pretty similar to
assert True
which is a pretty unexciting statement. Of course, I was both amused-and-not-amused when I started getting TypeErrors. Yes, it turns out that int(x) can return a long, which is not an int. Although I doubt that I'd prefer it throwing an exception, there seems to be something strongly disconnected here.

In any case, if you would like to make sure that your functions are being passed integers in the larger sense of the word, the statement you're going for is probably:
assert isinstance(x, (int, long))