So, I’ve been writing unit tests for some statistical code using py.test. One of the sweet things about py.test is that it gives you some cute context specific comparison assertions where you can check a data structure with another.
The problem that I ran into is when using this with floating point numbers. A minimal (convoluted) example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Now, this is not that annoying unless you wanna do this for complicated data structures such as dicts of lists of floats etc. and you want to use the assertion goodness that comes with py.test
. And I had exactly this situation at hand. Disclaimer: Don’t try this at work! Even though I did.
I was thinking that it’d be easy as pie to do this in a lisp by traversing the structure with a lambda that will round all the floats. And then I figured that Python can do this for me using the AST
module. There is a good introduction to the module here and a discussion on appropriate things to do with ASTs here.
So, here is what I ended up implementing (this is miles away from being safe to use) to solve the problem.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
And voila!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
|