0

I am using pytest to check for multi-line docstrings and the way I am testing to check for these multi-line comments involves making a temp file and using write() to write the docstring in and then search for it.

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

However I am unable to figure out how to write the actual docstring. For example, """hello""" would simply show up as hello

  • 4
    `"""` is simply a Python way of denoting multiline strings. It has nothing to do with docstrings. A docstring is the first non-assigned string of a function. You can use any quotation marks to denote it. Once printed, `"""X"""`, `"X"`, and `'X'` all become `X`. – DYZ Feb 12 '19 at 06:48
  • 2
    Of course, you could `hello_file.write('"""{}"""'.format(string))` if you want to write `string` in triple quotes. – tripleee Feb 12 '19 at 06:53
  • @tripleee Thank you, that worked. How about read it in too? Only one pair of quotations is seen. How do I get it to see the other too? – Mohammad Khan Feb 12 '19 at 08:23
  • You should probably understand the first comment above instead. – tripleee Feb 12 '19 at 08:24

2 Answers2

0

If I need to write docsting to file I will use this way to receive the docstring by using __doc__ attribute:

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

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

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

After that writing this docsting as regular string:

hello_file.write(some_function.__doc__)
Georgiy
  • 3,158
  • 1
  • 6
  • 18
0

As already said by comments """ is only showing a multiline string. If you just want to write a doc string to a file you can get the doc string directly from the function with __doc__ attribute. Then you can write it in whatever format you want to a file like this:

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"""')
Masoud Rahimi
  • 5,785
  • 15
  • 39
  • 67