Doctests: How to suppress/ignore output?

2024/9/16 23:25:19

The doctest of the following (nonsense) Python module fails:

"""
>>> L = []
>>> if True:
...    append_to(L) # XXX
>>> L
[1]
"""def append_to(L):L.append(1)class A(object):passreturn A()import doctest; doctest.testmod()

This is because the output after the line marked XXX is <__main__.A object at ...> (which is returned by append_to). Of course, I could put this output directly after the line marked XXX but in my case this would distract the reader from what shall be actually tested, namely the side effect of the function append_to. So how can I suppress that output or how can I ignore it. I tried it with:

"""
>>> L = []
>>> if True:
...    append_to(L) # doctest: +ELLIPSIS...
>>> L
[1]
"""def append_to(L):L.append(1)class A(object):passreturn A()import doctest; doctest.testmod()

However, this yields a ValueError: line 4 of the docstring for __main__ has inconsistent leading whitespace: ' ...'.

What I don't want to do is to change the line append_to(L) to something like _ = append_to(L) which would suppress the output, because the doctest is for documentation purposes and to show the reader how the module is supposed to be used. (In the case being documented, append_to should be used statement-like and not like a function. Writing _ = append_to(L) would deviate the reader from this.)

Answer

rewrite: This actually does work now; I realized that the "doctest" I had written earlier was actually not being parsed as the module docstring, so the test wasn't passing: it was just not being run.

I made sure to double-check this one.

__doc__ = """
>>> L = []
>>> if True:
...    append_to(L) # doctest: +IGNORE_RESULT
>>> L
[1]
""".replace('+IGNORE_RESULT', '+ELLIPSIS\n<...>')def append_to(L):L.append(1)class A(object):passreturn A()

I'm not sure if this qualifies as more readable or not. Note that there's nothing special about <...>: it will only work if the actual return value has that form, as it does in this case (i.e. it's <module.A object at 0x...>). The ELLIPSIS option makes ... "match any substring in the actual output" ¹. So I don't think there's a way to get it to match the entirety of the output.

update: To do this the "proper" way, it looks like you'd want to call doctest.register_optionflag('IGNORE_RESULT'), subclass doctest.OptionChecker, and arrange for an instance of that subclass to be used by the doctest. Presumably this means that running your doctest via $ python -m doctest your_module.py is not an option.

https://en.xdnf.cn/q/72865.html

Related Q&A

Matplotlib not showing xlabel in top two subplots

I have a function that Ive written to show a few graphs here:def plot_price_series(df, ts1, ts2):# price series line graphfig = plt.figure()ax1 = fig.add_subplot(221)ax1.plot(df.index, df[ts1], label=t…

SQLAlchemy NOT exists on subselect?

Im trying to replicate this raw sql into proper sqlalchemy implementation but after a lot of tries I cant find a proper way to do it:SELECT * FROM images i WHERE NOT EXISTS (SELECT image_idFROM events …

What is the correct way to obtain explanations for predictions using Shap?

Im new to using shap, so Im still trying to get my head around it. Basically, I have a simple sklearn.ensemble.RandomForestClassifier fit using model.fit(X_train,y_train), and so on. After training, Id…

value error when using numpy.savetxt

I want to save each numpy array (A,B, and C) as column in a text file, delimited by space:import numpy as npA = np.array([5,7,8912,44])B = np.array([5.7,7.45,8912.43,44.99])C = np.array([15.7,17.45,189…

How do I retrieve key from value in django choices field?

The sample code is below:REFUND_STATUS = ((S, SUCCESS),(F, FAIL) ) refund_status = models.CharField(max_length=3, choices=REFUND_STATUS)I know in the model I can retrieve the SUCCESS with method get_re…

Errno13, Permission denied when trying to read file

I have created a small python script. With that I am trying to read a txt file but my access is denied resolving to an no.13 error, here is my code:import time import osdestPath = C:\Users\PC\Desktop\N…

How to write large JSON data?

I have been trying to write large amount (>800mb) of data to JSON file; I did some fair amount of trial and error to get this code:def write_to_cube(data):with open(test.json) as file1:temp_data = j…

Using absolute_import and handling relative module name conflicts in python [duplicate]

This question already has answers here:How can I import from the standard library, when my project has a module with the same name? (How can I control where Python looks for modules?)(7 answers)Close…

Setting results of torch.gather(...) calls

I have a 2D pytorch tensor of shape n by m. I want to index the second dimension using a list of indices (which could be done with torch.gather) then then also set new values to the result of the index…

Why does PyCharm use double backslash to indicate escaping?

For instance, I write a normal string and another "abnormal" string like this:Now I debug it, finding that in the debug tool, the "abnormal" string will be shown like this:Heres the…