[Tutor] unwanted 'zero' ending
Peter Otten
__peter__ at web.de
Fri Jun 28 09:31:07 CEST 2013
Steven D'Aprano wrote:
> On 27/06/13 18:30, Peter Otten wrote:
>> Jim Mooney wrote:
>>
>>> On 27 June 2013 00:43, Alan Gauld <alan.gauld at btinternet.com> wrote:
>>>> Take the constant definitions out of the function....
>>>
>>> Since the program has an error And needs simplification (no doubt
>>> interdependent), but it would be hard to do both at once, this brings
>>> up a good general question: Is it best, in such cases, to correct the
>>> error, then simplify, or simplify, then correct the error?
>>
>> That depends. Ideally you'd have unittests to ensure that you aren't
>> introducing new errors with the simplification process.
>>
>> So if you don't have them already now is the time to formalize your
>> ad-hoc tests.
>
>
> Unit tests are great, but the learning curve is rather steep. I recommend
> that you start with doctests.
There is some overhead, e. g. to match your doctest you need
import unittest
from num_to_str import num_to_name
class TestNumToName(unittest.TestCase):
def test_valid(self):
self.assertEquals(
num_to_name(42),
"forty-two")
self.assertEquals(
num_to_name(3579),
"three thousand five hundred and seventy-nine")
That and assertRaises()
def test_invalid(self):
self.assertRaises(ValueError, num_to_name, -1)
self.assertRaises(TypeError, num_to_name, "7")
self.assertRaises(TypeError, num_to_name, None)
will take you a long way. doctest makes it easier to test functions that
print
def add(a, b):
print a + b
(look at
<http://hg.python.org/cpython/file/9046ef201591/Lib/test/test_dis.py>
to learn how this can be covered with unit tests) but I'd argue that mixing
calculations and output is never a good idea anyway. Also, there's no need
to use unittest exclusively.
> When you write a function, add a docstring ("documentation string") that
> explains what the function does. Include examples showing how it is
> expected to work:
>
>
> def num_to_name(number):
> """Return the English name of int number.
>
> >>> num_to_name(42)
> 'forty-two'
> >>> num_to_name(3579)
> 'three thousand five hundred and seventy-nine'
>
> """
> [code goes here as normal]
While one illustrative example or two even improve the docstring once you
add the corner cases it becomes too noisy for my taste.
Whatever approach you pick, unittest, doctest, or a combination, your code
will improve -- not just because you are verifying its correctness to some
extent, but also because the inherent question "How can I test it?" will
lead to a better overall structure.
More information about the Tutor
mailing list