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

D

David

Hello, how to add if...else... switch to doctest?
E.g. function outputs different value when global_var change.

"""
if (global_var == True):
[1,2]
else:
[1,2,3]
"""

Thank you very much.
 
T

Terry Reedy

Hello, how to add if...else... switch to doctest?
E.g. function outputs different value when global_var change.

"""
if (global_var == True):
function()
[1,2]
else:
function()
[1,2,3]
"""

doctests should/must be self contained. IE, you would have to set the
'global_var' in the doctext code itself.
.... if global_var: return [1,2]
.... else: return [1,2,3]
global_var = True
function() [1,2]
global_var = False
function()
[1,2,3]
 
S

Steven D'Aprano

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

Step 1):

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

... function()
... else:
... function()
[1, 2]
... 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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top