Skip to content

Instantly share code, notes, and snippets.

@uar316025
Created August 21, 2020 09:43
Show Gist options
  • Save uar316025/cdb488e0dbd0d5b147c9c753c696c811 to your computer and use it in GitHub Desktop.
Save uar316025/cdb488e0dbd0d5b147c9c753c696c811 to your computer and use it in GitHub Desktop.
ClosestTo utility class
from datetime import datetime, timedelta
DEFAULT_EPSILON = {
datetime: timedelta(seconds=5),
}
class ClosestTo:
"""Utility class to check value is closest to other"""
def __init__(self, origin_value, epsilon=None):
self.epsilon = epsilon or DEFAULT_EPSILON[type(origin_value)]
self.value = origin_value
def __eq__(self, other):
"""Perform check"""
if other is None:
return False
# difference in +epsilon to -epsilon range
return self.epsilon > (self.value - other) > -self.epsilon
def __repr__(self):
"""Representation"""
return f"ClosestTo({repr(self.value)}, epsilon={repr(self.epsilon)})"
# ==== EXAMPLE USAGE ====
def some_func():
... # some process
result['dt'] = datetime.now()
return result
def test_some_func():
result = some_func()
...
assert result['dt'] == ClosestTo(datetime.now())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment