Skip to content

Instantly share code, notes, and snippets.

@juanplopes
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanplopes/262de3050cc2c77b55f9 to your computer and use it in GitHub Desktop.
Save juanplopes/262de3050cc2c77b55f9 to your computer and use it in GitHub Desktop.
import unittest, numbers
class AlmostNumber:
def __init__(self, number, delta):
self.number = number
self.delta = delta
def __eq__(self, other):
return abs(self.number-other) < self.delta
def __repr__(self):
return repr(self.number)
def almost(obj, delta=1e-6):
if isinstance(obj, numbers.Number):
return AlmostNumber(obj, delta)
if isinstance(obj, dict):
return {almost(x, delta): almost(y, delta) for x, y in obj.items()}
if isinstance(obj, (list, tuple, set)):
return type(obj)(almost(x, delta) for x in obj)
return obj
class AlmostTest(unittest.TestCase):
def test_example(self):
self.assertEquals(almost([1, 2]), [1.0, 1.99999999999])
self.assertEquals(almost({'a':1, 'b':2}), {'a':1.0, 'b':1.99999999999})
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment