我在类方法中有一个包含docstrings的Python模块,在模块docstring中有一个真实的例子。区别在于方法文档字符串经过精心设计,是完全可重复的测试,而真实世界的例子只是Linux shell中历史的一个副本 - 它碰巧调用了python解释器。 p>
E.g。
"""
Real-world example:
# python2.5
Python 2.5 (release25-maint, Jul 20 2008, 20:47:25)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from packagename import module
>>> module.show_real_world_usage()
'Hello world!'
"""
class SomeClass(object):
def someMethod(self):
"""
>>> 1 == 1
True
"""
我想在SomeClass.someMethod
中运行doctest,但不在模块的docstrings中运行。
Doctest的+SKIP
指令仅适用于每行,这意味着在我的实际示例中添加10行。难看!
有没有办法让doctest跳过整个区块?有点像HTML中的<!-- ... -->
答案 0 :(得分:16)
在函数中包装示例,然后跳过函数调用:
"""
>>> def example():
... from packagename import module
... module.show_real_world_usage()
...
>>> example() # doctest: +SKIP
'Hello world!'
"""
答案 1 :(得分:6)
我的解决方案是修剪3个字符的>>>
和...
领导者,我希望doctest跳过它们,使它们成为2个字符。
所以
"""
>>> from packagename import module
>>> module.show_real_world_usage()
'Hello world!'
"""
已成为
"""
>> from packagename import module
>> module.show_real_world_usage()
'Hello world!'
"""
Epydoc并没有像doctests那样显示它,但我可以忍受这个。不过,欢迎使用doctest中的skip-until-further-notice指令。
答案 2 :(得分:2)
如果它不是任何实际的doctest,您只需将值赋给变量即可。例如,
example_usage = """
Real-world example:
# python2.5
...
"""
将导致不对“测试”进行评估。
使用__example_usage__
(或其他包含双下划线的内容)可能会更好,这样就可以清楚地知道这是一个“魔术”变量而不是在脚本上下文中使用的变量。
答案 3 :(得分:1)
建立在RobM's answer上的一个小变通办法是通过以>>>开头的示例来保留显示/格式,如下所示:
"""
>>>
>> from packagename import module
>> module.show_real_world_usage()
'Hello world!'
"""