[Python-Dev] (#19562) Asserts in Python stdlib code (datetime.py)

Alexander Belopolsky alexander.belopolsky at gmail.com
Fri Dec 13 18:56:14 CET 2013


On Fri, Nov 15, 2013 at 9:10 PM, Tim Peters <tim.peters at gmail.com> wrote:

> > _DI4Y   = _days_before_year(5)
> > # A 4-year cycle has an extra leap day over what we'd get from pasting
> > # together 4 single years.
> > assert _DI4Y == 4 * 365 + 1
> >
> > To me, the constant should be directly set to its known value.
> > _DI4Y = 4*365 + 1.
> > The function should then be tested in test_datetime.
> >   self.assertEqual(dt._days_before_year(5), dt._DI4Y)
>
> I think making that change would be pointless code churn.  Harmful,
> even.  As the guy who happened to have written that code ;-), I think
> it's valuable to have the _code_ (not off buried in some monstrously
> tedious test file) explain what the comments there do explain, and
> verify with the assert.  If anyone needs to muck with the
> implementation of datetime, it's crucial they understand what DI4Y
> _means_, and that it's identical to _days_before_year(5).  Its actual
> value (4*365 + 1) isn't really interesting.  Defining _DI4Y _as_
> _days_before_year(5) captures its _meaning_.
>


Interestingly, the corresponding C code is closer to what Terry suggested:

/* Number of days in 4, 100, and 400 year cycles.  That these have
 * the correct values is asserted in the module init function.
 */
#define DI4Y    1461    /* days_before_year(5); days in 4 years */
#define DI100Y  36524   /* days_before_year(101); days in 100 years */
#define DI400Y  146097  /* days_before_year(401); days in 400 years  */
...  skipping to the init function ...
    /* A 4-year cycle has an extra leap day over what we'd get from
     * pasting together 4 single years.
     */
    assert(DI4Y == 4 * 365 + 1);
    assert(DI4Y == days_before_year(4+1));

This is probably explainable by the limitations of the C language, but I
would find

_DI4Y = 4 * 365 + 1
assert _DI4Y == _days_before_year(5)

to be more natural than the way it is currently written.


>
> Ain't broke - don't fix.


Agree.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20131213/d847441d/attachment.html>


More information about the Python-Dev mailing list