From 217a7fbe614ef9b6cb269c51a4e952ee700ec31e Mon Sep 17 00:00:00 2001 From: Chad Birch Date: Fri, 5 Oct 2018 21:32:42 -0600 Subject: [PATCH] Refactor get_delta_from_subject() method Refactors the get_delta_from_subject() method for a few benefits: * Checks type more idiomatically (using isinstance instead of type) * Raise a TypeError if passed a type that isn't able to be handled * Return immediately if passed a timedelta, so the rest of the method doesn't need to be inside an else block --- ago.py | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/ago.py b/ago.py index 3b10557..b3d9760 100644 --- a/ago.py +++ b/ago.py @@ -4,18 +4,27 @@ units = ("year", "day", "hour", "minute", "second", "millisecond", "microsecond" def get_delta_from_subject(subject): - subject_type = type(subject) - if subject_type is timedelta: - delta = subject + """Convert the subject to a timedelta and return it.""" + if isinstance(subject, timedelta): + return subject + + if isinstance(subject, datetime): + dt = subject else: - if subject_type is int or subject_type is float: - dt = datetime.fromtimestamp(float(subject)) - else: - # assume subject is a datetime object and strip timezone data. - dt = subject.replace(tzinfo=None) - # finally, create a timedelta from datetime. - delta = datetime.now() - dt - return delta + # if it's not a datetime, assume it's a unix timestamp + try: + subject = float(subject) + except ValueError: + # some unknown type that couldn't be converted to a float + raise TypeError("Unsupported subject type") + + dt = datetime.fromtimestamp(subject) + + # strip timezone data + dt = dt.replace(tzinfo=None) + + # finally, return a timedelta from the datetime + return datetime.now() - dt def delta2dict(delta):