[Python-Dev] (#19562) Asserts in Python stdlib code (datetime.py)
Terry Reedy
tjreedy at udel.edu
Sat Nov 16 02:51:30 CET 2013
http://bugs.python.org/issue19562
propose to change the first assert in Lib/datetime.py
assert 1 <= month <= 12, month
to
assert 1 <= month <= 12,'month must be in 1..12'
to match the next two asserts out of the *53* in the file. I think that
is the wrong direction of change, but that is not my question here.
Should stdlib code use assert at all?
If user input can trigger an assert, then the code should raise a normal
exception that will not disappear with -OO.
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)
Is there any policy on use of assert in stdlib production code?
--
Terry Jan Reedy
More information about the Python-Dev
mailing list