Add if...else... switch to doctest?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Oct 18 21:57:37 EDT 2012


On Thu, 18 Oct 2012 17:08:37 -0700, David wrote:

> Hello, how to add if...else... switch to doctest? 

Step 1): 

Write your doctest with the switch. Don't forget to test both branches:


    >>> global_var = True
    >>> if global_var:
    ...     function()
    ... else:
    ...     function()
    [1, 2]

    >>> global_var = False
    >>> if global_var:
    ...     function()
    ... else:
    ...     function()
    [1, 2, 3]


Step 2): realise that this is a stupid thing to do, and re-write the 
doctest without the if test:

    >>> global_var = True
    >>> function()
    [1, 2]
    >>> global_var = False
    >>> function()
    [1, 2, 3]


Step 3): realise that this is a stupid design for a function, you're not 
writing BASIC in 1976, and global variables are harmful. Redesign the 
function to take an argument and re-write the doctest:

    >>> function(True)
    [1, 2]
    >>> function(False)
    [1, 2, 3]


And now you have good code and a good doctest.




-- 
Steven



More information about the Python-list mailing list