如何在python中使用write()将docstring写入文件?

2024-05-20 07:16:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用pytest检查多行docstring,检查这些多行注释的测试方法包括创建一个临时文件并使用write()写入docstring,然后搜索它。在

def test_file_contains_multiline_python_comment_count(tmpdir):
    """Checks that the multiline python comment count works"""
    hello_file = tmpdir.mkdir("subdirectory").join("Hello.py")
    hello_file.write(""" hello \n world """)
    assert hello_file.read() == """ hello \n world """
    assert len(tmpdir.listdir()) == 1
    comment_count = entities.count_entities(
        hello_file.basename, hello_file.dirname, comments.count_multiline_python_comment
    )
    assert comment_count == 1

但是,我无法理解如何编写实际的docstring。例如,"""hello"""将简单地显示为hello


Tags: testhelloworldpytestdefcountcommentassert
2条回答

正如注释所说,"""只显示一个多行字符串。如果您只想将doc字符串写入一个文件,那么可以直接从具有__doc__属性的函数中获取doc字符串。然后您可以将它以任何格式写入如下文件:

def test():
    """
    This is docstring of the test function
    """
    return "Hello"

if __name__ == "__main__":
    with open("out.txt", "w") as f:
        f.write('"""\n' + (test.__doc__).strip() + '\n"""')

如果需要将docsting写入文件,我将使用this方式通过使用__doc__属性接收docstring:

def some_function():
    """some docstring
    multiline""" 
    return 0

>>>    some_function.__doc__
    'some docstring\n    multiline'

>>>    type(some_function.__doc__)
    <class 'str'>

在将此docsting作为常规字符串写入之后:

^{pr2}$

相关问题 更多 >