[Terry Reedy]
> Should stdlib code use assert at all?

Of course, and for exactly the same reasons we use `assert()` in
Python's C code:  to verify preconditions, postconditions, and
invariants that should never fail.  Assertions should never be used
to, e.g., verify user-supplied input (or anything else we believe
_may_ fail).

> If user input can trigger an assert, then the code should raise a normal
> exception that will not disappear with -OO.

Agreed.

> If the assert is testing program logic, then it seems that the test belongs
> in the test file, in this case, test/test_datetime.py. For example, consider
> the following (backwards) code.

> _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_.

Ain't broke - don't fix.
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to