[Tutor] unwanted 'zero' ending

Steven D'Aprano steve at pearwood.info
Thu Jun 27 14:38:38 CEST 2013


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.


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]




The examples must be formatted as if they were copied and pasted from the standard Python interpreter, complete with leading >>> prompt. The doctest module will detect those examples, run them, and report on any errors. From the shell:


python -m doctest "C:/path/to/module/to/test.py"


If there are no errors, doctest won't print anything, otherwise it will print any errors. An error is:

* anything that raises an exception;

* anything that returns something other than the example shown.


To see all the tests as they run:

python -m doctest "C:/path/to/module/to/test.py" --verbose


Once you get used to the quirks of doctest, and there are a few, I hope you will love it as much as I do. They make both great documentation and good tests!



-- 
Steven


More information about the Tutor mailing list