datelib pythonification

John Machin sjmachin at lexicon.net
Sun Feb 21 04:16:11 EST 2010


On Feb 21, 12:37 pm, alex goretoy <agore... at gmail.com> wrote:
> hello all,
>     since I posted this last time, I've added a new function dates_diff and

[SNIP]

I'm rather unsure of the context of this posting ... I'm assuming that
the subject "datelib pythonification" refers to trying to make
"datelib" more "pythonic", with which you appear to need help.

Looking just at the new "function" (looks like a method to me)
dates_diff, problems include:

1. Mostly ignores PEP-8 about spaces after commas, around operators
2. Checks types
3. Checks types using type(x) == type(y)
4. Inconsistent type checking: checks types in case of
dates_diff(date1, date2) but not in case of dates_diff([date1, date2])
5. Doesn't check for 3 or more args.
6. The 0-arg case is for what purpose?
7. The one-arg case is overkill -- if the caller has the two values in
alist, all you are saving them from is the * in dates_diff(*alist)
8. Calling type(date.today()) once per 2-arg call would be a gross
extravagance; calling it twice per 2-arg call is mind-boggling.
9. start,end=(targs[0][0],targs[0][1]) ... multiple constant
subscripts is a code smell; this one is pongier than usual because it
could easily be replaced by start, end = targs[0]

Untested fix of problems 1, 3, 4, 5, 8, 9:

DATE_TYPE = type(date.today())

def dates_diff(self, *targs):
    nargs = len(targs)
    if nargs == 0:
        return self.enddate - self.startdate
    if nargs == 1:
        arg = targs[0]
        if not isinstance(arg, (list, tuple)) or len(arg) != 2:
            raise Exception(
                "single arg must be list or tuple of length 2")
        start, end = arg
    elif nargs == 2:
        start, end = targs
    else:
        raise Exception("expected 0,1, or 2 args; found %d" % nargs)
    if isinstance(start, DATE_TYPE) and isinstance(end, DATE_TYPE):
        return end - start
    raise Exception("both values must be of type DATE_TYPE")

HTH,

John




More information about the Python-list mailing list